将数据帧转换为从列名到列名的宽到长多个列

2024-09-29 17:14:06 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑到我有一个具有以下格式的熊猫数据文件。

Date           Product cost|us|2019    cost|us|2020    cost|us|2021  cost|de|2019    cost|de|2020  cost|de|2021
01/01/2020     prodA   10              12              14            12              13            15

我们如何将其转换为以下格式

Date         Product      Year     cost|us      cost|de
01/01/2020   ProdA        2019     10           12
01/01/2020   ProdA        2020     12           13
01/01/2020   ProdA        2021     14           15

Tags: date数据文件格式deproductyearuscost
1条回答
网友
1楼 · 发布于 2024-09-29 17:14:06

将非年份列按^{}转换为MultiIndex,然后按最后一列按|使用^{},在^{}中设置新列nmae,并按^{}重新整形:

df = df.set_index(['Date','Product'])
df.columns = df.columns.str.rsplit('|', n=1, expand=True)
df = df.rename_axis([None, 'Year'], axis=1).stack().reset_index()
print (df)
         Date Product  Year  cost|de  cost|us
0  01/01/2020   prodA  2019       12       10
1  01/01/2020   prodA  2020       13       12
2  01/01/2020   prodA  2021       15       14

相关问题 更多 >

    热门问题