【发布时间】:2019-07-16 15:24:56
【问题描述】:
我有一个面板数据集df
stock year date return
VOD 2017 01-01 0.05
VOD 2017 01-02 0.03
VOD 2017 01-03 0.04
... ... ... ....
BAT 2017 01-01 0.05
BAT 2017 01-02 0.07
BAT 2017 01-03 0.10
所以我使用此代码来获取每年每只股票的回报的均值和偏度。
df2=df.groupby(['stock','year']).mean().reset_index()
df3=df.groupby(['stock','year']).skew().reset_index()
df2 和 df3 看起来不错。
df2 就像(在我更改列名之后)
stock year mean_return
VOD 2017 0.09
BAT 2017 0.14
... ... ...
df3 就像(在我更改列名之后)
stock year return_skewness
VOD 2017 -0.34
BAT 2017 -0.04
... ... ...
问题是当我尝试使用合并 df2 和 df3 时
want=pd.merge(df2,df2, on=['stock','year'],how='outer')
python给了我
'The column label 'stock' is not unique.
For a multi-index, the label must be a tuple with elements corresponding to each level.'
,这让我很困惑。
我可以使用want = pd.merge(df2,df3, left_index=True, right_index=True, how='outer') 合并df2 和df3,但之后我必须重命名列,因为列名在括号中。
有没有方便的方法来合并 df2 和 df3 ?谢谢
【问题讨论】:
标签: pandas dataframe indexing merge multi-index