如何为python中列中的每个唯一值创建一个虚拟值 [英] How to create a dummy for every unique value in a column in python
本文介绍了如何为python中列中的每个唯一值创建一个虚拟值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框
,其中包含行上的产品及其特征.
I have a data frame
with products on rows and their characteristics.
我希望为每个特征列中的每个唯一值创建一个新的虚拟变量,如果该特定产品存在此特定特征值,则该虚拟变量为 1,否则为 0.
I would like for every unique value in every characteristics column, to create a new dummy variable, which will have 1 if this specific characteristic value exists for that specific product and 0 otherwise.
举个例子:
import pandas as pd
df = pd.DataFrame({'id':['prod_A','prod_A','prod_B','prod_B'],
'color':['red','green','red','black'],
'size':[1,2,3,4]})
我想以这样的 data frame
结束:
and I would like to end up with a data frame
like this:
df_f = pd.DataFrame({'id': ['prod_A', 'prod_B'],
'color_red': [1, 1],
'color_green': [1, 0],
'color_black': [0, 1],
'size_1': [1, 0],
'size_2': [1, 0],
'size_3': [0, 1],
'size_4': [0, 1]})
有什么想法吗?
推荐答案
使用 get_dummies
与聚合 max
:
#dummies for all columns without `id`
df = pd.get_dummies(df.set_index('id')).max(level=0).reset_index()
<小时>
#dummies for columns in list
df = pd.get_dummies(df, columns=['color','size']).groupby('id', as_index=False).max()
<小时>
print (df)
id color_black color_green color_red size_1 size_2 size_3 size_4
0 prod_A 0 1 1 1 1 0 0
1 prod_B 1 0 1 0 0 1 1
这篇关于如何为python中列中的每个唯一值创建一个虚拟值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文