如何解决在列 Python 中有多个级别
我在一个数据框中有几列 - 每列都有几个因素/级别 (10+) 。在每一列中,3-4 个因子占值的 85-90%。我在数据中有几列。遍历每一列并制作前 3-4 名的虚拟变量将花费大量时间。简单地放置 get_dummies 会成倍地增加数据的大小。是否有任何有用的方法可以建议我可以自动将前 3-4 个因素作为虚拟变量,将其余因素推入“其他”类别,对于每一列?我正在使用 python
解决方法
您可以按列找到 nlargest
,并在创建虚拟对象时将不在前 3 中的值替换为其他值。
import pandas as pd
df = pd.DataFrame({'type':['a','a','b','c','d','e'],'size': ['s','s','m','l','xl']})
for col in ['type','size']:
df = pd.concat([df,pd.get_dummies(df[col].replace(df.loc[~df[col].isin(df[col].value_counts().nlargest(3).index)][col].unique(),'other'),prefix=col)],axis=1)
输出
type size type_a type_b type_c type_other size_l size_m size_other \
0 a s 1 0 0 0 0 0 0
1 a s 1 0 0 0 0 0 0
2 a s 1 0 0 0 0 0 0
3 b m 0 1 0 0 0 1 0
4 b m 0 1 0 0 0 1 0
5 b s 0 1 0 0 0 0 0
6 c l 0 0 1 0 1 0 0
7 d l 0 0 0 1 1 0 0
8 e xl 0 0 0 1 0 0 1
size_s
0 1
1 1
2 1
3 0
4 0
5 1
6 0
7 0
8 0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。