【问题标题】:Transpose one row to column in Pandas在 Pandas 中将一行转换为列
【发布时间】:2021-07-23 22:14:42
【问题描述】:
考虑下表:我为每个状态的每个 year 和 age 设置了一些值。
| Age |
Year |
State1 |
State2 |
State3 |
| 1 |
2010 |
123 |
456 |
789 |
| 2 |
2010 |
111 |
222 |
333 |
| 1 |
2011 |
444 |
555 |
666 |
| 2 |
2011 |
777 |
888 |
999 |
现在我想以这样的方式转置表格,使Year 成为列:
| Age |
State |
2010 |
2011 |
| 1 |
State1 |
123 |
444 |
| 1 |
State2 |
456 |
555 |
| 1 |
State3 |
789 |
666 |
| 2 |
State1 |
111 |
777 |
| 2 |
State2 |
222 |
888 |
| 2 |
State3 |
333 |
999 |
我无法让它工作,只转置特定的列。
在 Pandas 中实现这一目标的好方法是什么?
【问题讨论】:
标签:
python
pandas
transpose
【解决方案1】:
你要找的是pd.melt
我们可以结合应用自定义索引和取消堆栈来使用它
df1 = pd.melt(df,id_vars=['Year','Age'],var_name=['State'])
out = df1.set_index([df1.groupby(['Year']).cumcount(),'Year','State','Age'])\
.unstack('Year').droplevel(0,1).reset_index([1,2])
Year State Age 2010 2011
0 State1 1 123 444
1 State1 2 111 777
2 State2 1 456 555
3 State2 2 222 888
4 State3 1 789 666
5 State3 2 333 999
【解决方案2】:
您可以堆叠和取消堆叠您的数据框:
out = (
df.set_index(["Age", "Year"])
.stack()
.unstack("Year")
.reset_index()
.rename(columns={"level_1": "State"})
)
Year Age State 2010 2011
0 1 State1 123 444
1 1 State2 456 555
2 1 State3 789 666
3 2 State1 111 777
4 2 State2 222 888
5 2 State3 333 999