我有一个包含多个类别变量的数据框,需要将其转换为虚拟变量。使用pd.get_dummies
可以轻松实现性别和区域(4种类型)。但是,此后我有几个变量是yes/no
。我该怎么做才能使伪yes
和no
列包含变量名?例如,“已婚”变量将变成married_yes
和married_no
?
这是我当前的代码和前五行的屏幕截图:
genderdummy=pd.get_dummies(bank_df['gender'])
regiondummy=pd.get_dummies(bank_df['region'])
marrieddummy=pd.get_dummies(bank_df['married'])
cardummy=pd.get_dummies(bank_df['car'])
savingsdummy=pd.get_dummies(bank_df['savings_acct'])
currentdummy=pd.get_dummies(bank_df['current_acct'])
mortgagedummy=pd.get_dummies(bank_df['mortgage'])
pepdummy=pd.get_dummies(bank_df['pep'])
newdata_df=pd.concat([genderdummy,regiondummy,marrieddummy,cardummy,savingsdummy,currentdummy,mortgagedummy,pepdummy], axis=1)
newdata_df.head()
因此,根据建议,这是我现在拥有的:
## HW Part 6: Converting Categorical Variables and Exporting Data
genderdummy=pd.get_dummies(bank_df['gender'])
regiondummy=pd.get_dummies(bank_df['region'])
dummy_vars = [bank_df('married'), bank_df('car'),bank_df('savings_acct'),bank_df('current_acct'),bank_df('mortgage'),bank_df('pep')]
pd.get_dummies(bank_df[dummy_vars])
newdata_df=pd.concat([genderdummy,regiondummy,dummy_vars], axis=1)
newdata_df.head()
答案 0 :(得分:4)
如果更改方法,它将自动执行此操作。您只需要在数据框而不是序列上调用pd.get_dummies
:
import numpy as np
import pandas as pd
# Define sample data and columns for dummy variables
df = pd.DataFrame(np.random.choice(['yes', 'no'], size=(6, 3)), columns=['gender', 'region', 'married'])
dummy_vars = ['gender', 'married']
# Create dummy variables
pd.get_dummies(df[dummy_vars])
gender_no gender_yes married_no married_yes
0 0 1 1 0
1 1 0 0 1
2 0 1 1 0
3 1 0 1 0
4 1 0 1 0
5 0 1 1 0
或者您可以使用prefix
参数来明确显示
pd.get_dummies(df[dummy_vars], prefix=dummy_vars)
更新:
使用变量,它应该像这样:
genderdummy = pd.get_dummies(bank_df['gender'])
regiondummy = pd.get_dummies(bank_df['region'])
dummy_vars = ['married', 'car', 'savings_acct', 'current_acct', 'mortgage', 'pep']
other_dummies = pd.get_dummies(bank_df[dummy_vars])
newdata_df = pd.concat([genderdummy, regiondummy, other_dummies], axis=1)
newdata_df.head()
注意dummy_vars
只是bank_df
中列的名称。
答案 1 :(得分:2)
在pandas.get_dummies()中使用prefix
参数
df = pd.DataFrame({'text':['cat', 'dog','cat','dog']})
df = pd.get_dummies(df['text'], prefix='text')
print(df)
输出
text_cat text_dog
0 1 0
1 0 1
2 1 0
3 0 1