Sahil Kamboj
Sahil Kamboj

Reputation: 418

How to create columns from matching data?

Data that I have:

    df = pd.DataFrame(pd.DataFrame([('Bus Route A', 'Beach Station'),
 ('Bus Route B', 'Village Hotel '),
 ('Bus Route A', 'Amara Sanctuary Resort'),
 ('Bus Route C', 'Village Hotel '),
 ('Bus Route B', 'Beach Station'),
 ('Bus Route C', 'Beach Station')]))

enter image description here

What I is need is:

Upvotes: 0

Views: 39

Answers (1)

jezrael
jezrael

Reputation: 862511

Use crosstab with comapre for greater or equal 1 and cast mask to integers:

df = pd.crosstab(df[1], df[0]).ge(1).astype(int)
print (df)
0                       Bus Route A  Bus Route B  Bus Route C
1                                                            
Amara Sanctuary Resort            1            0            0
Beach Station                     1            1            1
Village Hotel                     0            1            1


print (df.reset_index().apply(tuple, axis=1).tolist())
[('Amara Sanctuary Resort', 1, 0, 0), 
 ('Beach Station', 1, 1, 1), 
 ('Village Hotel ', 0, 1, 1)]

Upvotes: 3

Related Questions