2

I know pandas has a get_dummies() function. What i'm trying to do is not just put a 1/0 value to it but to use the values from another column for it.

I have the following example:

Id A B
1 a 1
2 a 2
3 b 3
4 b 4
5 b 5
6 c 6

I want to turn this into:

ID A_a A_b A_c
1 1 0 0
2 2 0 0
3 0 3 0
4 0 4 0
5 0 5 0
6 0 0 6

Where the values for the dummary variables are from column B. ID is short for identification.

1 Answer 1

5

You can get_dummies for column 'A' and multiply column B:

pd.get_dummies(df['A'],prefix='A').mul(df['B'],axis=0)

    A_a  A_b  A_c
Id               
1     1    0    0
2     2    0    0
3     0    3    0
4     0    4    0
5     0    5    0
6     0    0    6
Sign up to request clarification or add additional context in comments.

Comments

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.