简体   繁体   中英

Using get_dummies() with more than a column

I want to use get_dummies() with more than a coulmn. ( 'CabinNumber', 'Name' contain strings ) when i delete one of them and use xtr = pd.get_dummies(x['Name']) my code works

I tried everything in this answer . However i could not get my code to work.

 x = df.loc[df['Price'].notnull(), ['Age','Fee', 'Size','Class','CabinNumber', 'Name' ]]

I tried:

xtr = pd.get_dummies(data=x, columns=['CabinNumber', 'Name'])

I tried:

xtr = pd.get_dummies(df.loc[df['Price'].notnull(), ['Age','Fee', 'Size','Class','CabinNumber', 'Name' ]])

I tried replicating your code and mine works fine.

data = {'a': ['foo', 'buzz'], 'b':['cookie', 'milk'], 'Price': ['super',
   ...:  'duper']}

x = df.loc[df['Price'].notnull(), ['a', 'b']]
>>>       a       b
0   foo  cookie
1  buzz    milk

xtr = pd.get_dummies(data=x, columns = x.columns)
xtr
>>>    a_buzz  a_foo  b_cookie  b_milk
0     0.0    1.0       1.0     0.0
1     1.0    0.0       0.0     1.0

Edit: You could also do this as per the thread you linked

pd.concat([pd.get_dummies(x[col]) for col in x], axis=1, keys=x.columns)

Pandas version=0.24.2, assume your original dataframe = df

dfdummies = pd.get_dummies(data=df,columns=['Gender','Designation'])

It performs the creation of dummy variables and also concat data to original dataframe.So, no need to add extra line for concatenation or merging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM