Pandas 数据框从宽到长的多列转换,名称来自列名称 [英] Pandas dataframe covert wide to long multiple columns with name from column Name
本文介绍了Pandas 数据框从宽到长的多列转换,名称来自列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑我有一个具有以下格式的 Pandas 数据框.
Consider I have a Pandas Dataframe with the following format.
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
我们如何将其转换为以下格式?
How can we convert it into the following format?
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
推荐答案
通过 DataFrame.set_index
,然后使用 str.rsplit
按列按最后 |
, 在 DataFrame.rename_axis
并通过 DataFrame.stack
:
Convert non year columns to MultiIndex
by DataFrame.set_index
, then use str.rsplit
by columns by last |
, set new column nmae in DataFrame.rename_axis
and reshape by DataFrame.stack
:
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
这篇关于Pandas 数据框从宽到长的多列转换,名称来自列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文