如何取消堆叠数据框
How to unstack dataframe
我有一个 pandas df,其中包含 708 行的“项目”、“年份”、“值”列。我想将其重塑为 59 行 12 列的 df。
这是现在的样子(简化):
Item, Year, Value
Apple, 2001, 5
Apple, 2002, 4
Apple, 2003, 7
Apple, 2004, 2
Orange, 2001, 1
Orange, 2002, 5
Orange, 2003, 2
Orange, 2004, 3
而我需要的结果是:
Year, Apple, Orange
2001, 5, 1
2002, 4, 5
2003, 7, 2
2004, 2, 3
我怎样才能实现这一目标?谢谢!
您只需要先将 Year
和 Item
设置为索引,然后就很容易了:
In [331]: df.set_index(["Year", "Item"]).unstack()['Value']
Out[331]:
Item Apple Orange
Year
2001 5 1
2002 4 5
2003 7 2
2004 2 3
print(df.pivot(index="Year", columns="Item", values="Value"))
打印:
Item Apple Orange
Year
2001 5 1
2002 4 5
2003 7 2
2004 2 3
要保存为 CSV:
x = df.pivot(index="Year", columns="Item", values="Value").reset_index()
x.to_csv("data.csv", index=False)
节省 data.csv
:
Year,Apple,Orange
2001,5,1
2002,4,5
2003,7,2
2004,2,3
我有一个 pandas df,其中包含 708 行的“项目”、“年份”、“值”列。我想将其重塑为 59 行 12 列的 df。 这是现在的样子(简化):
Item, Year, Value
Apple, 2001, 5
Apple, 2002, 4
Apple, 2003, 7
Apple, 2004, 2
Orange, 2001, 1
Orange, 2002, 5
Orange, 2003, 2
Orange, 2004, 3
而我需要的结果是:
Year, Apple, Orange
2001, 5, 1
2002, 4, 5
2003, 7, 2
2004, 2, 3
我怎样才能实现这一目标?谢谢!
您只需要先将 Year
和 Item
设置为索引,然后就很容易了:
In [331]: df.set_index(["Year", "Item"]).unstack()['Value']
Out[331]:
Item Apple Orange
Year
2001 5 1
2002 4 5
2003 7 2
2004 2 3
print(df.pivot(index="Year", columns="Item", values="Value"))
打印:
Item Apple Orange
Year
2001 5 1
2002 4 5
2003 7 2
2004 2 3
要保存为 CSV:
x = df.pivot(index="Year", columns="Item", values="Value").reset_index()
x.to_csv("data.csv", index=False)
节省 data.csv
:
Year,Apple,Orange
2001,5,1
2002,4,5
2003,7,2
2004,2,3