[英]How to transform a 2nd level category column with values to multiple columns
I'd like to transform a "category" index from a DataFrame
with MultiIndex
into multiple columns each holding the values of the row they belonged to before.我想将带有
MultiIndex
的DataFrame
的“类别”索引MultiIndex
为多列,每列都包含它们之前所属行的值。 My index columns are Index
and Country
.我的索引列是
Index
和Country
。
Index Country Count
0 'Canada' 10
'Italy' 20
1 'Indonesia' 5
'Canada' 2
2 'Italy' 14
To:到:
Canada Indonesia Italy
0 10 0 20
1 2 5 0
2 0 0 14
It is quite close to the get_dummies
function but I need to keep the count values to their correct positions.它非常接近
get_dummies
函数,但我需要将计数值保持在正确的位置。
If one column DataFrame
with MultiIndex
select column with Series.unstack
:如果一个
DataFrame
用MultiIndex
与选择列Series.unstack
:
df1 = df['Count'].unstack(fill_value=0)
print (df1)
Country 'Canada' 'Indonesia' 'Italy'
Index
0 10 0 20
1 2 5 0
2 0 0 14
If MultiIndex Series
:如果多
MultiIndex Series
:
df1 = s.unstack(fill_value=0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.