I am trying to use isin funtion in the if condtion within a function but it gives me an error
I have function f
, and I am passing columns A
from the dataframe df
, and my if condition should check if A in ('IND','USA')
then return visited_countries else not_visited_countries
def f(A)
if A.isin(['IND','USA']):
return Visited_countries
else:
return not_visited_countries
df['D']=df.apply(lambda x: f(x.A,axis=1)
when I execute this code it give the below error
AttributeError: ("'str' object has no attribute 'isin'", 'occurred at index 0')
Please let me know what I am missing here.
You need to use Series, not all DF, eg column A in DF so :
if DF.A.isin(['IND','USA']).any():
You may want this
df.loc[df.A.isin(['IND','USA']),'D'] = 'Visited_countries'
df.loc[~df.A.isin(['IND','USA']),'D'] = 'Not_visited_countries'
or you want to use if condition, I think you might use 'in' keyword. What about this?
df['D'] = df.A.apply(lambda x : 'Visited_countries' if x in ['IND','USA'] else 'Not_visited_countries')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With