Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform values from 1 column to multiple columns

Tags:

pandas

I have the following table:

enter image description here

and would like to convert the product column to something like:

enter image description here

How would you recomend I do this in pandas? Test df below

import numpy as np
import pandas as pd

test_dict = {'Acount': ['1', '2', '3', '4'], 'Product': [np.nan, 'A','A,B,C', 'C']}
df = pd.DataFrame.from_dict(test_dict)
like image 587
Brandon Avatar asked Dec 11 '25 07:12

Brandon


1 Answers

For a single column you can use Series.str.get_dummies which allows you to specify the character that separates all categories. Set 'Acount' to the index so that appears in the output:

df.set_index('Acount')['Product'].str.get_dummies(sep=',')

        A  B  C
Acount         
1       0  0  0
2       1  0  0
3       1  1  1
4       0  0  1
like image 125
ALollz Avatar answered Dec 15 '25 17:12

ALollz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!