繁体   English   中英

从具有多个日期/价格列的数据框在 Pandas 中创建面板

[英]Create a panel in pandas from a dataframe with several date/price columns

我在 Pandas 中有一个数据框,其中包含资产 1_date、资产 1_价格、资产 2_日期、资产 2_价格等列(最多约 500 个资产)。 asset1_date 和 asset2_date 不一定相同。 我想将其重新格式化为一个面板,其中一列称为资产,然后一列表示日期,一列表示价格,即

pd.DataFrame({'asset':['asset1','asset1','asset2','asset2','asset2'],'date':['09/26/2003','09/29/2003','04/10/2007','04/11/2007','04/12/2007'],'price':[102,103,75,74,76]})

目前,数据如下:

pd.DataFrame({'asset1_date':['09/26/2003','09/29/2003',np.nan],'asset1_price':[102,103,np.nan],'asset2_date':['04/10/2007','04/11/2007','04/12/2007'],'asset2_price':[75,74,76]})

谁能建议一个大熊猫方法来实现这一目标? 谢谢!

这应该可以解决问题:

df=df.stack().reset_index()
df["asset"]=df["level_1"].str.split("_").str[0]
df["col"]=df["level_1"].str.split("_").str[1]
df=df.set_index(["level_0", "col", "asset"]).unstack("col").reset_index("level_0", drop=True).reset_index("asset", drop=False).drop("level_1", axis=1, level=0)
#please note this following line is a bit of a brute force approach, since I'm assuming you want exactly these columns, alternative you can find in here:
#https://stackoverflow.com/a/47979382/11610186
df.columns=["asset", "date", "price"]

输出:

    asset        date price
0  asset1  09/26/2003   102
1  asset2  04/10/2007    75
2  asset1  09/29/2003   103
3  asset2  04/11/2007    74
4  asset2  04/12/2007    76

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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