Reputation: 4575
I'm very new to Python and was hoping someone might be able to give me some tips. I'm also new to posting on stack over flow, so any tips on how to display a table in it would definitely be appreciated as well.
Anyways, I have two columns D and J as pictured in the before area below. I would like to create a new table as shown in the after area below where I create columns from the unique values in the J column and add a 1 in each row to indicate the record had the unique value. Someone suggested get_dummies from the pandas library. I'm working in the pandas library, but again I'm very new. Thanks again for any advice.
Before:
D | J
A | 1q
B | 2E
C | 7F
After:
D | 1q |2E | 7F
A | 1 |
B | .. | 1
C | .. | .. | 1
Upvotes: 1
Views: 424
Reputation: 128948
In [45]: pd.get_dummies(df['J'])
Out[45]:
1q 2E 7F
D
A 1 0 0
B 0 1 0
C 0 0 1
Upvotes: 1
Reputation: 11717
It works, but not really straightforward
import pandas as pd
df = pd.DataFrame.from_dict({'D': ['A', 'B', 'C'] ,'J':['1q', '2E', '7F']})
df = df.set_index('D')
uniqueJ = df['J'].unique()
res=pd.concat([df['J']==v for v in uniqueJ],axis=1)
res.columns=uniqueJ
res=res.applymap(lambda x: 1 if x else 0)
Upvotes: 0