对Pandas DataFrame中的groupBy数据应用规范化

时间:2017-07-07 06:33:06

标签: python pandas dataframe data-analysis

DataFrame列:

['PercentSalaryHike', 'Attrition', 'EmployeeCountFraction']

按前两列分组后: EmployeeCount显示人员的 部分 ,其损耗 '是' 并且休息 '否对于特定 PercentSalaryHike

DataFrame

重置索引后,DataFrame如下所示:

enter image description here

我想要的是应用规范化来简化DataFrame。 应该是这样的:

PercentSalaryHike   Attrition-Yes    Attrition-No

11                    0.195238       0.804762
12                    0.166667       0.833333
13                    0.837321       0.163351
..
..
..

我给出的样本在2个字段上应用了groupBy。我想要一个通用的解决方案,按这种方式对按n个字段分组的数据进行规范化。

1 个答案:

答案 0 :(得分:1)

我认为您需要unstack来重塑数据,然后add_prefixreset_index和最后rename_axis

df = df['EmployeeCountFraction'].unstack()
                                .add_prefix('Attrition-')
                                .reset_index()
                                .rename_axis(None, axis=1)
print (df)
   PercentSalaryHike  Attrition-No  Attrition-Yes
0                 11      0.804762       0.195238
1                 12      0.833333       0.166667
2                 13      0.837321       0.163351
相关问题