gpt4 book ai didi

python - 从具有多个字符串的列制作 get_dummies 类型数据框的最快方法

转载 作者:太空狗 更新时间:2023-10-29 18:00:12 25 4
gpt4 key购买 nike

我有一列“col2”,其中包含一个字符串列表。我当前的代码太慢了,大约有 2000 个唯一字符串(下例中的字母)和 4000 行。最终为 2000 列和 4000 行。

In [268]: df.head()
Out[268]:
col1 col2
0 6 A,B
1 15 C,G,A
2 25 B

有没有一种快速的方法可以将其转换为 get dummies 格式?每个字符串都有自己的列,如果该行在 col2 中有该字符串,则在每个字符串的列中有一个 0 或 1。

In [268]: def get_list(df):
d = []
for row in df.col2:
row_list = row.split(',')
for string in row_list:
if string not in d:
d.append(string)
return d

df_list = get_list(df)

def make_cols(df, lst):
for string in lst:
df[string] = 0
return df

df = make_cols(df, df_list)


for idx in range(0, len(df['col2'])):
row_list = df['col2'].iloc[idx].split(',')
for string in row_list:
df[string].iloc[idx]+= 1

Out[113]:
col1 col2 A B C G
0 6 A,B 1 1 0 0
1 15 C,G,A 1 0 1 1
2 25 B 0 1 0 0

这是我目前的代码,但它太慢了。

谢谢你的帮助!

最佳答案

您可以使用:

>>> df['col2'].str.get_dummies(sep=',')
A B C G
0 1 1 0 0
1 1 0 1 1
2 0 1 0 0

加入数据框:

>>> pd.concat([df, df['col2'].str.get_dummies(sep=',')], axis=1)
col1 col2 A B C G
0 6 A,B 1 1 0 0
1 15 C,G,A 1 0 1 1
2 25 B 0 1 0 0

关于python - 从具有多个字符串的列制作 get_dummies 类型数据框的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28121682/

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