user7269547
user7269547

Reputation:

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' ]])

Upvotes: 2

Views: 3165

Answers (2)

ambar mishra
ambar mishra

Reputation: 64

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.

Upvotes: 0

gold_cy
gold_cy

Reputation: 14216

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)

Upvotes: 1

Related Questions