gpt4 book ai didi

python - 在多个 bool 列中拆分 Pandas 数据框列

转载 作者:太空宇宙 更新时间:2023-11-04 02:28:20 25 4
gpt4 key购买 nike

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

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

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

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

问题 1:如何首先确定流派列中的所有唯一流派标题?

问题 2:在我确定了所有独特的流派标题后,如何创建所有必要的 ['insert genre' yes/no] 列?

最佳答案

使用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 - 在多个 bool 列中拆分 Pandas 数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49814741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com