7

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

3
  • pass a dict to use replace on the df: df.replace({'True':1,'False':0}) Commented Sep 26, 2016 at 9:11
  • You could also do this in your function itself: df['eq'] = df.apply(lambda row: 1 if row['coname1'] == row['coname2'] else 0, axis=1) Commented Sep 26, 2016 at 9:16
  • I've been struggling with replace boolean values with integer too! converting a boolean call to int seems to be the best way, right now, if you want 0 or 1 Commented Apr 5, 2017 at 10:25

1 Answer 1

19

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

Sign up to request clarification or add additional context in comments.

1 Comment

typo in line 1. astype() .. panda docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.