How do i add data in dataframe under the columns and across the rows?


Keywords:python 


Question: 

I have a few dataframes that are loaded previously from CSV files

b = portfolionew_df.loc [1,['x_1','x_2','x_3','x_4','x_5']]
x = [stockprice_df.loc[ :, b]]
print(x)

This is the result for x:

NYSEARCA:RYE  NYSEARCA:XOP  NYSEARCA:PXE  NYSEARCA:VAW  NYSEARCA:PYZ  
 0           68.37         52.00         25.37         87.94         35.00
 1           60.70         48.04         22.64         83.78         32.61
 2           67.04         54.48         24.70         86.61         34.44
 3           65.86         53.75         24.16         84.94         34.21

c = pd.DataFrame(index=(time_df['Date']),columns=(b))
print(c)

This is the result for c:

Date        NYSEARCA:RYE    NYSEARCA:XOP    NYSEARCA:PXE    NYSEARCA:VAW    NYSEARCA:PYZ

2007-12-31  NaN             NaN             NaN             NaN           NaN
2008-01-31  NaN             NaN             NaN             NaN           NaN
2008-02-29  NaN             NaN             NaN             NaN           NaN
2008-03-31  NaN             NaN             NaN             NaN           NaN

The content is all NaN because i did not manage to add data in. How can i achieve this?

Date    NYSEARCA:RYE    NYSEARCA:XOP    NYSEARCA:PXE    NYSEARCA:VAW    NYSEARCA:PYZ

2007-12-31  68.37         52.00         25.37         87.94         35.00
2008-01-31  60.70         48.04         22.64         83.78         32.61
2008-02-29  67.04         54.48         24.70         86.61         34.44
2008-03-31  65.86         53.75         24.16         84.94         34.21

My aim is to add the data from x into c dataframe. How can i do it?


2 Answers: 

As your data is in x and index in time_df, you can do:

  c=x
  c=c.set_index(time_df['Date'])
  print c


IIUC by using combine_first

c.reset_index().combine_first(x)
Out[523]: 
         Date  NYSEARCA:PXE  NYSEARCA:PYZ  NYSEARCA:RYE  NYSEARCA:VAW  \
0  2007-12-31         25.37         35.00         68.37         87.94   
1  2008-01-31         22.64         32.61         60.70         83.78   
2  2008-02-29         24.70         34.44         67.04         86.61   
3  2008-03-31         24.16         34.21         65.86         84.94   
   NYSEARCA:XOP  
0         52.00  
1         48.04  
2         54.48  
3         53.75