0

I have a dataframe like below

   A             B          
Customer_1    1000      
Customer_1    2000      
Customer_1    3000      
Customer_2    2000      
Customer_2    3000      
Customer_3    1000      
Customer_3    3000      

I want to transform the above dataframe like below , how can i make it ?

A             B           3000      2000    1000
Customer_1    1000         0         0       1
Customer_1    2000         0         1       1
Customer_1    3000         1         1       1
Customer_2    2000         0         1       0
Customer_2    3000         1         1       0
Customer_3    1000         0         0       1
Customer_3    3000         1         0       1

I cant figure out how to do this,please help me on this and let me know if you need clarification.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114

1 Answers1

0

Use get_dummies, of the str accessor, also use join to merge:

print(df.join(df.B.astype(str).str.get_dummies()))

Output:

            A     B  1000  2000  3000
0  Customer_1  1000     1     0     0
1  Customer_1  2000     0     1     0
2  Customer_1  3000     0     0     1
3  Customer_2  2000     0     1     0
4  Customer_2  3000     0     0     1
5  Customer_3  1000     1     0     0
6  Customer_3  3000     0     0     1

It's really just merging df with that value with 0, 1, how the 0, 1 is done? use get_dummies which does it all by itself.

Edit:

print(df.join(df.join(df.groupby('A').apply(lambda x: x['B'].astype(str).str.get_dummies()).fillna(0).astype(int)).groupby('A').cumsum().drop('B',1)))

Output:

            A     B  1000  2000  3000
0  Customer_1  1000     1     0     0
1  Customer_1  2000     1     1     0
2  Customer_1  3000     1     1     1
3  Customer_2  2000     0     1     0
4  Customer_2  3000     0     1     1
5  Customer_3  1000     1     0     0
6  Customer_3  3000     1     0     1
U13-Forward
  • 69,221
  • 14
  • 89
  • 114