[英]Pivot pandas dataframe to have multi-indexed columns
I am struggling with how to pivot the dataframe to have multi-indexed columns.我正在努力解决如何让 pivot 和 dataframe 拥有多索引列。
I have a dataframe like this:我有一个像这样的 dataframe:
data = pd.DataFrame({"name":["a", "a", "b", "b", "b", "b", "c", "c"],
"month":[1, 1, 2, 3, 1, 1, 1, 3],
"buy_sell":["sell", "buy", "sell", "buy", "sell", "buy", "sell", "buy"],
"value":[10, 20, 30, 40, 20, 80, 50, 60]})
data
And I want to pivot this to a wide format.我想把 pivot 这个改成宽格式。 index is
name
, and for columns I want to create multi-index with the combination of month
and buy_sell
index 是
name
,对于列,我想结合month
和buy_sell
创建多索引
Or if not multi-indexed columns, I want to pivot the dataframe so that the columns have the suffices such as sell_1
, buy_1
, sell_2
, buy_2
etc...或者,如果不是多索引列,我想 pivot dataframe 使列具有足够的功能,例如
sell_1
, buy_1
, sell_2
, buy_2
等...
Any help would be appreciated.任何帮助,将不胜感激。 Thank you!
谢谢!
You can use set_index()
and unstack()
:您可以使用
set_index()
和 unstack( unstack()
:
(data.set_index(['name','month','buy_sell'])['value']
.unstack(['month','buy_sell']))
Output: Output:
month 1 2 3
buy_sell sell buy sell buy
name
a 10.0 20.0 NaN NaN
b 20.0 80.0 30.0 40.0
c 50.0 NaN NaN 60.0
If you insist on having those columns with all NaN
, you can unstack
one level at a time:如果您坚持让这些列全部包含
NaN
,则可以一次unstack
一层:
(data.set_index(['name','month','buy_sell'])['value']
.unstack('month').unstack('buy_sell')
)
Output: Output:
month 1 2 3
buy_sell buy sell buy sell buy sell
name
a 20.0 10.0 NaN NaN NaN NaN
b 80.0 20.0 NaN 30.0 40.0 NaN
c NaN 50.0 NaN NaN 60.0 NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.