python - 在列中按值添加百分比列
问题描述
我正在尝试将分类列值编码为百分比频率(二进制编码)作为新功能。
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%
解决方案
用于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) + '%'
推荐阅读
- karate - 空手道穿过 mvn 终端 - Nashorn 为空
- scala - 如何将变量 onlineID 记录到 Gatling 日志
- android - toString() 显示数字,而不是我使用 R.string 时的文本
- css - 删除与多个其他 Dom 元素共享类名的图标/按钮
- javascript - 传单Angular中的.on函数内的addEventListener
- azure-pipelines - Azure Pipeline 和 .NET Framework 项目
- java - 如何在测试中禁用骆驼组件?
- javascript - 如何使用 mongoose 匹配 Mongodb 中对象数组内的键
- html - 如何并排放置两个反应组件?
- javascript - 如何基于响应对象创建条件,其键值依赖并避免 object.key() 未定义