Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas replace boolean value with string or integer

This is snipett of my code with column values comparison:

import pandas as pd
df =pd.DataFrame({'coname1':['Apple','Yahoo','Gap Inc'],'coname2':['Apple', 'Google', 'Apple']})
df['eq'] =df.apply(lambda row: row['coname1'] == row['coname2'],axis=1)

The problem is that I am interested with Character (True='Y' or False = 'N') or Integer (True= 1 or False = 0) values.

Option df.replace(['True', 'False'],[1,0]) doesn't work Thank you

like image 395
Felix Avatar asked Sep 26 '16 09:09

Felix


1 Answers

When assigning the 'eq' column, use atype(int). The int conversion turns True into 1 and False into 0

df = pd.DataFrame({'coname1': ['Apple','Yahoo','Gap Inc'], 'coname2':['Apple', 'Google', 'Apple']})
df['eq'] = df.apply(lambda row: row['coname1'] == row['coname2'], axis=1).astype(int)

For characters

df['eq'] = np.where(df['eq'], 'Y', 'N')
df

enter image description here

like image 112
piRSquared Avatar answered Sep 30 '22 15:09

piRSquared