python - 将 pandas 数据框列拆分为多个 bool 列

标签 python pandas dataframe

我有一个包含 10K 行电影数据的 csv。

在“流派”列中,数据如下所示:

Adventure|Science Fiction|Thriller
Action|Adventure|Science Fiction|Fantasy
Action|Crime|Thriller
Western|Drama|Adventure|Thriller

我想根据类型列创建多个子列(即 Action 是/否、冒险是/否、戏剧是/否等)。

问题 1:我如何首先确定流派列中的所有独特流派标题?

问题 2:在我确定所有独特的流派标题后,如何创建所有必要的['插入流派'是/否]列?

最佳答案

使用str.get_dummies :

df = df['col'].str.get_dummies('|').replace({0:'no', 1:'yes'})

或者:

d = {0:'no', 1:'yes'}
df = df['col'].str.get_dummies('|').applymap(d.get)

为了获得更好的性能,请使用 MultiLabelBinarizer :

from sklearn.preprocessing import MultiLabelBinarizer

mlb = MultiLabelBinarizer()
df = (pd.DataFrame(mlb.fit_transform(df['col'].str.split('|')) ,
                   columns=mlb.classes_, 
                   index=df.index)
        .applymap(d.get))

print (df)
  Action Adventure Crime Drama Fantasy Science Fiction Thriller Western
0     no       yes    no    no      no             yes      yes      no
1    yes       yes    no    no     yes             yes       no      no
2    yes        no   yes    no      no              no      yes      no
3     no       yes    no   yes      no              no      yes     yes

详细信息:

print (df['col'].str.get_dummies('|'))
   Action  Adventure  Crime  Drama  Fantasy  Science Fiction  Thriller  \
0       0          1      0      0        0                1         1   
1       1          1      0      0        1                1         0   
2       1          0      1      0        0                0         1   
3       0          1      0      1        0                0         1   

   Western  
0        0  
1        0  
2        0  
3        1  

时间:

df = pd.concat([df] * 10000, ignore_index=True)


In [361]: %timeit pd.DataFrame(mlb.fit_transform(df['col'].str.split('|')) ,columns=mlb.classes_,  index=df.index)
10 loops, best of 3: 120 ms per loop

In [362]: %timeit df['col'].str.get_dummies('|')
1 loop, best of 3: 324 ms per loop

In [363]: %timeit pd.get_dummies(df['col'].str.split('|').apply(pd.Series).stack()).sum(level=0)
1 loop, best of 3: 7.77 s per loop

关于python - 将 pandas 数据框列拆分为多个 bool 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49814741/

相关文章:

python - 如何在 Python 3.3.5 中添加矩阵的对角线

python - 艰难地学习Python ex24

Javascript 词法分析器/分词器(在 Python 中?)

python - 如何正确舍入数据框列?

r - 在 R 图中使用 data.frame 的行名称?

python - 使用 lxml 和 xpath 从 python ElementTree 中提取多个值

python-3.x - python中矩阵中的多个字符替换

python - 查找每列的最新行

python - 使用随机 'nicknames' 对 pandas 名称列进行匿名化

python - 按对角线旋转数据框