如何在列和行之间的数据框中添加数据?

问题描述 投票:0回答:2

我有一些以前从CSV文件加载的数据帧

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

这是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)

这是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

内容全部是NaN,因为我没有设法添加数据。我怎样才能实现这一目标?

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

我的目标是将x中的数据添加到c数据帧中。我该怎么做?

python pandas dataframe jupyter-notebook
2个回答
0
投票

由于您的数据位于x和time_df中的索引中,您可以执行以下操作:

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

0
投票

IIUC使用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  
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.