熊猫:将多个类别转换为假人

Ste*_*reo 6 python pandas

我有一个表,每行可以属于多个类别,如,

test = pd.DataFrame({
            'name': ['a', 'b'],
            'category': [['cat1', 'cat2'],['cat1', 'cat3']]
    })
Run Code Online (Sandbox Code Playgroud)

如何以上表所示的方式将每个类别转换为虚拟变量,

test_res = pd.DataFrame({
        'name': ['a', 'b'],
        'cat1': [1, 1],
        'cat2': [1, 0],
        'cat3': [0, 1]
    })
Run Code Online (Sandbox Code Playgroud)

我试过pd.get_dummies(test['category'])但得到以下错误,

TypeError: unhashable type: 'list'
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 9

您可以使用pandas.get_dummies,但首先将list列转换为新列DataFrame:

print (pd.DataFrame(test.category.values.tolist()))
      0     1
0  cat1  cat2
1  cat1  cat3

print (pd.get_dummies(pd.DataFrame(test.category.values.tolist()), prefix_sep='', prefix=''))
   cat1  cat2  cat3
0     1     1     0
1     1     0     1
Run Code Online (Sandbox Code Playgroud)

最后加列nameconcat:

print (pd.concat([pd.get_dummies(pd.DataFrame(test.category.values.tolist()),
                                 prefix_sep='', prefix='' ), 
        test[['name']]], axis=1))
   cat1  cat2  cat3 name
0     1     1     0    a
1     1     0     1    b
Run Code Online (Sandbox Code Playgroud)

另一个解决方案Series.str.get_dummies:

print (test.category.astype(str).str.strip('[]'))
0    'cat1', 'cat2'
1    'cat1', 'cat3'
Name: category, dtype: object

df = test.category.astype(str).str.strip('[]').str.get_dummies(', ')
df.columns = df.columns.str.strip("'")
print (df)
   cat1  cat2  cat3
0     1     1     0
1     1     0     1

print (pd.concat([df, test[['name']]], axis=1))
   cat1  cat2  cat3 name
0     1     1     0    a
1     1     0     1    b
Run Code Online (Sandbox Code Playgroud)