python - Pandas :将多个类别转换为假人

标签 python pandas

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

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

如何将每个类别转换为虚拟变量,使上表变为,

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

我尝试了 pd.get_dummies(test['category']) 但出现以下错误,

TypeError: unhashable type: 'list'

最佳答案

您可以使用 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

最后添加列 name by concat :

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

另一种解决方案 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

关于python - Pandas :将多个类别转换为假人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40213177/

相关文章:

python - 创建双箱线图 - 即每个 x 值有两个框

python - 由于没有考虑后面的字符,str.match 不完全匹配

python - Pandas/Numpy 从数组列中获取矩阵

python - 修复了带有线程锁的 strptime 异常,但会减慢程序速度

python - Django 中的单选按钮

python - 如何从键值对列表创建 Spark Row

Python 使用 numpy\pandas 选择多个范围

python - 如何统计Python字典中总值的频率?

python - 如果在数据帧列中找到则返回字符串的关键字

Python 选择和计数元素