简体   繁体   中英

Creating multiple dataframes from 2 data frames basis dates in Python

I am new to Python and would need some help with my problem:

I have a dataframe that looks something like this: df1

date       col1 col2 col3
01-01-2008  nan 16  19
02-01-2008  nan 25  20
03-01-2008  nan nan nan
04-01-2008  18  18  nan

I have another dataframe that looks like: df2

start        end         col4
01-01-2008  04-01-2008  [col1,col2]
02-01-2008  04-01-2008  [col1]
03-01-2008  04-01-2008  [col3]

I need to write a code such that I have values of col1 col2 from date 1-1-2008 to 4-1-2008 stored in one dataframe and values of col1 from 02-01-2008-04-01-2008 stored in another dataframe and so forth.

Basically I want my output something like this: df3

date       col1 col2
01-01-2008  nan 16
02-01-2008  nan 25
03-01-2008  nan nan
04-01-2008  18  18

df4

date       col1
02-01-2008  nan
03-01-2008  nan
04-01-2008  18

df5

date        col3
03-01-2008  nan
04-01-2008  nan

Please Help!!

Try this and let me know if you face any problem. Here you go:

for i in range(len(df2)):
    start = df2["start"][i]
    end = df2["end"][i]
    cols = df2["col4"][i].replace("[","").replace("]","").split(",")
    print(df1.set_index("date",drop=True).loc[[df1[start:end]],cols])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM