Pandas 将行中的列表分隔为列和一个热编码
Pandas separate list in row to columns and one hot encode
客户的在线表单将多选选项输出到以逗号分隔的单个字段。有没有一种方法可以将值拆分成列并对它们进行热编码,我正在使用 pandas?
现在数据:
id | ind
1 | Student, Tourism, Industrial
2 | Residential, Student, Tourism
3 | student, Tourism, Industrial, Education
我想要数据的方式:
id | ind_student| ind_Tourism| ind_Industrial| ind_Residential| ind_Education
1 | 1 | 1 | 1 | 0 | 0
2 | 1 | 1 | 0 | 1 | 0
3 | 1 | 1 | 1 | 0 | 1
感谢观看!
将您的 ind
列拆分为单词并旋转您的数据框:
out = df.assign(ind=df['ind'].str.split(', '), dummy=1).explode('ind') \
.pivot_table('dummy', 'id', 'ind', fill_value=0).add_prefix('ind_')
print(out)
# Output:
ind ind_Education ind_Industrial ind_Residential ind_Student ind_Tourism ind_student
id
1 0 1 0 1 1 0
2 0 0 1 1 1 0
3 1 1 0 0 1 1
使用get_dummies。但是,首先通过创建列表和分解将每个字符串放入其行中。因为大小写混合,请首字母大写,然后crosstab
df=df.assign(ind=df['ind'].str.title().str.strip().str.split(',')).explode('ind')
df=pd.crosstab(df['id'], df['ind']).add_prefix('ind_')
ind ind_Education ind_Industrial ind_Residential ind_Student ind_Tourism
id
1 0 1 0 1 1
2 0 0 1 1 1
3 1 1 0 1 1
客户的在线表单将多选选项输出到以逗号分隔的单个字段。有没有一种方法可以将值拆分成列并对它们进行热编码,我正在使用 pandas?
现在数据:
id | ind
1 | Student, Tourism, Industrial
2 | Residential, Student, Tourism
3 | student, Tourism, Industrial, Education
我想要数据的方式:
id | ind_student| ind_Tourism| ind_Industrial| ind_Residential| ind_Education
1 | 1 | 1 | 1 | 0 | 0
2 | 1 | 1 | 0 | 1 | 0
3 | 1 | 1 | 1 | 0 | 1
感谢观看!
将您的 ind
列拆分为单词并旋转您的数据框:
out = df.assign(ind=df['ind'].str.split(', '), dummy=1).explode('ind') \
.pivot_table('dummy', 'id', 'ind', fill_value=0).add_prefix('ind_')
print(out)
# Output:
ind ind_Education ind_Industrial ind_Residential ind_Student ind_Tourism ind_student
id
1 0 1 0 1 1 0
2 0 0 1 1 1 0
3 1 1 0 0 1 1
使用get_dummies。但是,首先通过创建列表和分解将每个字符串放入其行中。因为大小写混合,请首字母大写,然后crosstab
df=df.assign(ind=df['ind'].str.title().str.strip().str.split(',')).explode('ind')
df=pd.crosstab(df['id'], df['ind']).add_prefix('ind_')
ind ind_Education ind_Industrial ind_Residential ind_Student ind_Tourism
id
1 0 1 0 1 1
2 0 0 1 1 1
3 1 1 0 1 1