dataframe—在python列中具有多个级别

fcy6dtqo  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(184)

我在一个 Dataframe 中有几个列-每个列都有几个因子/级别(10+)。在每列中,3-4个因子占数值的85-90%。我在数据中有几列。浏览每一列并制作前3-4的虚拟变量将花费大量时间。简单地放置get_假人将使数据的大小成倍增加。是否有任何有用的方法可以建议我自动将前3-4个因素作为虚拟变量,将其余因素推到“其他”类别中,用于每个列?我正在使用python

9rbhqvlz

9rbhqvlz1#

你可以找到 nlargest 按列,并在创建假人时用其他值替换不在前3中的值。

import pandas as pd

df = pd.DataFrame({'type':['a','a','a','b','b','b','c','d','e'],
                  'size': ['s','s','s','m','m','s','l','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

相关问题