从具有多个字符串的列制作 get_dummies 类型数据框的最快方法 [英] Quickest way to make a get_dummies type dataframe from a column with a multiple of strings
问题描述
我有一列col2",其中包含一个字符串列表.我当前的代码太慢了,大约有 2000 个唯一字符串(下面示例中的字母)和 4000 行.最终为 2000 列和 4000 行.
在 [268]: df.head()出[268]:列 1 列 20 6 A,B1 15 C,G,A2 25 乙
有没有一种快速的方法可以以 get dummies 格式制作它?每个字符串都有自己的列,如果该行在 col2 中有该字符串,则在每个字符串的列中都有一个 0 或 1.
在 [268]: def get_list(df):d = []对于 df.col2 中的行:row_list = row.split(',')对于 row_list 中的字符串:如果字符串不在 d 中:d.追加(字符串)返回df_list = get_list(df)def make_cols(df, lst):对于 lst 中的字符串:df[字符串] = 0返回 dfdf = make_cols(df, df_list)对于范围内的 idx(0, len(df['col2'])):row_list = df['col2'].iloc[idx].split(',')对于 row_list 中的字符串:df[字符串].iloc[idx]+= 1出[113]:col1 col2 A B C G0 6 A,B 1 1 0 01 15 C,G,A 1 0 1 12 25 乙 0 1 0 0
这是我当前的代码,但它太慢了.
谢谢你的帮助!
您可以使用:
<预><代码>>>>df['col2'].str.get_dummies(sep=',')A B C G0 1 1 0 01 1 0 1 12 0 1 0 0加入数据框:
<预><代码>>>>pd.concat([df, df['col2'].str.get_dummies(sep=',')],axis=1)col1 col2 A B C G0 6 A,B 1 1 0 01 15 C,G,A 1 0 1 12 25 乙 0 1 0 0I have a column, 'col2', that has a list of strings. The current code I have is too slow, there's about 2000 unique strings (the letters in the example below), and 4000 rows. Ending up as 2000 columns and 4000 rows.
In [268]: df.head()
Out[268]:
col1 col2
0 6 A,B
1 15 C,G,A
2 25 B
Is there a fast way to make this in a get dummies format? Where each string has it's own column and in each string's column there is a 0 or 1 if it that row has that string in col2.
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
This is my current code for it but it's too slow.
Thanks you any help!
You can use:
>>> 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
To join the Dataframes:
>>> 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
这篇关于从具有多个字符串的列制作 get_dummies 类型数据框的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!