简体   繁体   中英

Creating dummy variable with values from another column

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.

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

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