Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a string column into several boolean columns using pandas

Tags:

python

pandas

I have a two columned data set that I would like to reshape.
Looking at this fake df:

df=pd.DataFrame([
    ['Alex', 'Apple'],['Bob', 'Banana'],['Clark', 'Citrus'], ['Diana', 'Banana'], [
'Elisa', 'Apple'], ['Frida', 'Citrus'], ['George', 'Citrus'], ['Hanna', 'Banana']
],columns=['Name', 'Fruit'])

I would like to have four columns; Name, Apple, Banana and Citrus where the three latter are booleans (true/false).
I've looked inte unstack but it's really not what I am looking for.

like image 685
Mactilda Avatar asked Dec 11 '22 03:12

Mactilda


2 Answers

I think this should be a good use case for get_dummies:

df.set_index('Name')['Fruit'].str.get_dummies().astype(bool).reset_index()

     Name  Apple  Banana  Citrus
0    Alex   True   False   False
1     Bob  False    True   False
2   Clark  False   False    True
3   Diana  False    True   False
4   Elisa   True   False   False
5   Frida  False   False    True
6  George  False   False    True
7   Hanna  False    True   False

In similar vein, we have,

pd.concat([df['Name'], df['Fruit'].str.get_dummies().astype(bool)], axis=1)

     Name  Apple  Banana  Citrus
0    Alex   True   False   False
1     Bob  False    True   False
2   Clark  False   False    True
3   Diana  False    True   False
4   Elisa   True   False   False
5   Frida  False   False    True
6  George  False   False    True
7   Hanna  False    True   False
like image 107
cs95 Avatar answered Dec 12 '22 15:12

cs95


You can use the below:

df[['Name']].join(pd.get_dummies(df.Fruit).astype(bool))

     Name  Apple  Banana  Citrus
0    Alex   True   False   False
1     Bob  False    True   False
2   Clark  False   False    True
3   Diana  False    True   False
4   Elisa   True   False   False
5   Frida  False   False    True
6  George  False   False    True
7   Hanna  False    True   False
like image 39
anky Avatar answered Dec 12 '22 17:12

anky