简体   繁体   中英

How can I add parts of a column to a new pandas data frame?

So I have a pandas data frame of lenght 90 which isn't important Lets say I have :

df

A   date
1   2012-01-01
4   2012-02-01
5   2012-03-01
7   2012-04-01
8   2012-05-01
9   2012-06-01
2   2012-07-01
1   2012-08-01
3   2012-09-01
2   2012-10-01
5   2012-11-01
9   2012-12-01
0   2013-01-01
6   2013-02-01

and I have created a new data frame

df_copy=df.copy() 
index = range(0,3)
df1 = pd.DataFrame(index=index, columns=range((len(df_copy.columns))))
df1.columns = df_copy.columns                     

df1['date'] = pd.date_range('2019-11-01','2020-01-01' , freq='MS')-pd.offsets.MonthBegin(1)

which should create a data frame like this

A   date
na   2019-10-01
na   2019-11-01
na   2019-12-01

So I use the following code to get the values of A in my new data frame

df1['A'] = df1['A'].iloc[9:12]

And I want the outcome to be this

A   date
2   2019-10-01
5   2019-11-01
9   2019-12-01

so I want that the last 3 values are assigned the value that has iloc position 9-12 in the new data frame, the indexes are different and so are the dates in both data frames. Is there a way to do this because

 df1['A'] = df1['A'].iloc[9:12]

doesn't seem to work

According to my knowledge you can solve this by genearting several new data frames

df_copy=df.copy() 
index = range(0,1)
df1 = pd.DataFrame(index=index, columns=range((len(df_copy.columns))))
df1.columns = df_copy.columns                     

df1['date'] = pd.date_range('2019-11-01','2019-11-01' , freq='MS')-pd.offsets.MonthBegin(1)
df1['A'] = df1['A'].iloc[9]

Then appending to your original data frame and repeating it is a bit overwhemling but it seems like the only solution i could came up with

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