简体   繁体   English

如何将具有值的第二级类别列转换为多列

[英]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.我想将带有MultiIndexDataFrame的“类别”索引MultiIndex为多列,每列都包含它们之前所属行的值。 My index columns are Index and Country .我的索引列是IndexCountry

 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 :如果一个DataFrameMultiIndex与选择列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.

相关问题 如何在pandas DataFrame中将二级索引更改为二级列? - How to change 2nd level index into 2nd level column in pandas DataFrame? Pandas multindex DataFrame:用第二级其他列的值替换某些值 - Pandas multindex DataFrame: replace certain values by values from other column on 2nd level 如何删除具有特定 1 级和 2 级索引的多行? - How to drop multiple rows with certain 1st level and 2nd level index? Pandas:Groupby两列并计算第二列的所有值的出现次数 - Pandas: Groupby two columns and count the occurence of all values for 2nd column 合并多个文件:第一列(相同的字符串),第二列(每个文件的唯一值) - Merge multiple files: 1st Column (same string), 2nd Column (unique values per file) 如何将多个数据框合并到一个多索引数据框,其中每个合并的数据框都成为第二级列 - how to merge mulitple dataframes to one multiindex dataframe where each of merged dataframes becomes 2nd level column 如何根据 Pandas 中第一个数据框中的某些列值从第二个数据框中添加列值 - How to add Column Values from 2nd DataFrame Based on Some Column Values in First dataframe in Pandas 如何删除行索引的第二列? - How to drop the 2nd column of row index? 如何numpy searchsorted将1列上的2个值的范围平分,并在第2列中获取最小值 - How to numpy searchsorted bisect a range of 2 values on 1 column and get min value in 2nd column 如何检查 1 个数据帧中的列中的整数值是否存在于第 2 个数据帧中 2 列之间的范围拆分中? - How do I check for an integer value in a column in 1 dataframe to exist in a range split between 2 columns in 2nd dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM