使用get_dummies时删除冗余列

时间:2018-05-04 13:27:15

标签: python pandas categorical-data

你有一个包含分类变量的pandas数据帧df

df=pandas.DataFrame(data=[['male','blue'],['female','brown'],
['male','black']],columns=['gender','eyes'])

df
Out[16]: 
   gender   eyes
0    male   blue
1  female  brown
2    male  black

使用函数get_dummies我得到以下数据框

df_dummies = pandas.get_dummies(df)

df_dummies
Out[18]: 
   gender_female  gender_male  eyes_black  eyes_blue  eyes_brown
0              0            1           0          1           0
1              1            0           0          0           1
2              0            1           1          0           0

Owever列gender_femalegender_male包含相同的信息,因为原始列可以采用二进制值。是否有(智能)方法只保留2列中的一列?

已更新

使用

df_dummies = pandas.get_dummies(df,drop_first=True)

会给我

df_dummies
Out[21]: 
   gender_male  eyes_blue  eyes_brown
0            1          1           0
1            0          0           1
2            1          0           0

但我想删除原本只有2种可能性的列

期望的结果应该是

df_dummies
Out[18]: 
   gender_male  eyes_black  eyes_blue  eyes_brown
0  1           0          1           0
1  0           0          0           1
2  1           1          0           0

2 个答案:

答案 0 :(得分:2)

是的,您可以使用参数dropfirst

drop_first=True

来自documentation

pd.get_dummies(pd.Series(list('abcaa')), drop_first=True)
   b  c
0  0  0
1  1  0
2  0  1
3  0  0
4  0  0

要为eyes创建所有虚拟列,为gender创建一个虚拟列,请使用:

df = pd.get_dummies(df, prefix=['eyes'], columns=['eyes'])
df = pd.get_dummies(df,drop_first=True)

输出:

       eyes_black  eyes_blue  eyes_brown  gender_male
0           0          1           0            1
1           0          0           1            0
2           1          0           0            1

更一般:

   gender   eyes    heigh
0    male   blue     tall
1  female  brown    short
2    male  black  average

for i in df.columns:
    if len(df.groupby([i]).size()) > 2:
         df = pd.get_dummies(df, prefix=[i], columns=[i])
df = pd.get_dummies(df, drop_first=True)

输出:

   eyes_black  eyes_blue  eyes_brown  heigh_average  heigh_short  heigh_tall  \
0           0          1           0              0            0           1   
1           0          0           1              0            1           0   
2           1          0           0              1            0           0    

   gender_male  
0            1  
1            0  
2            1

答案 1 :(得分:0)

您可以使用itertools.combinations查找所有列对,然后任何可能冗余的列对将是每行一列为True而另一列为False - 即异或:

import pandas as pd
from itertools import combinations

df = pd.DataFrame(data=[['male','blue'],['female','brown'],['male','black']],
                  columns=['gender','eyes'])

dummies = pd.get_dummies(df)

for c1, c2 in combinations(dummies.columns, 2):
    if all(dummies[c1] ^ dummies[c2]):
        print(c1,c2)

然而,这也注意到在你的例子中所有女性都有棕色眼睛,因此我们得到以下印刷品:

gender_female gender_male
gender_male eyes_brown