首页 > 解决方案 > 在列中按值添加百分比列

问题描述

我正在尝试将分类列值编码为百分比频率(二进制编码)作为新功能。

Value   Count   Frequency (%) 
20190   14723   16.2%    
20100   11235   12.4%    
20120   9449    10.4%    
20130   7744    8.5%     
20210   5920    6.5%     
20140   5192    5.7%     
20270   4324    4.8%     
20220   3800    4.2%     
20180   3707    4.1%     
20110   3031    3.3%     
Other values (28)   21572   23.8%

我试过这个:

df1['binary_group_of_materials']=df1['A_group_of_materials'].value_counts(normalize=True) * 100

有一个新列,但所有值都是 NaN。

输出应该是:

Value   Frequency (%) 
20190   16.2%    
20100   12.4%    
20120   10.4%    
20130   8.5%     
20210   6.5%     
20140   5.7%     
20270   4.8%     
20220   4.2%     
20180   4.1%     
20110   3.3%     

标签: pythonpandasencodingcategorical-datafeature-selection

解决方案


用于Series.map新列:

s = df1['A_group_of_materials'].value_counts(normalize=True) * 100
df1['binary_group_of_materials'] = df1['A_group_of_materials'].map(s)

如果需要百分比:

df1['binary_group_of_materials'] = df1['A_group_of_materials'].map(s).round(1).astype(str) + '%'

推荐阅读