0

I'm thinking to convert multiple columns of categorical variables in a data frame to dummy variables using pandas. The code below works, but it seems too long. May I know how do I combine these 3 lines in a single line of code, please? Thank you

X = pd.get_dummies(df.height, prefix=['height'])

Y = pd.get_dummies(df.weight, prefix=['weight'])

Z = pd.get_dummies(df.age, prefix=['age'])**

1 Answer 1

1

You can use:

pd.get_dummies(data=df, columns=["height", "weight", "age"])
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks the code works well but I would like to save these 3 variables into another variable called "J". so I used J = pd.get_dummies(data=df, columns=["height", "weight", "age"]). However, 2 other columns in the original data frame appear as well. How do I exclude these 2 columns?
A possible approach could be to create a list with the new column names: new_cols = ["name1", "name2", "name3"] and then create the new dataframe as J = J[new_cols].
@NicoleOppenheim for clarity, please provide the expected output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.