I have a data frame and a list. I want to check if strings in column ends with anything in my list. I want to create a new column showing if column ends with anything in the list then value is "Y", other wiese "N". my data frame Data looks like following:
import pandas as pd
city = ['New York', 'Los Angeles','Buffalo','Miami','San Deigo', 'San
Francisco']
population = ['8.5','3.9','0.25','0.45','1.4','0.87']
df = pd.DataFrame({'city':city,'population':population})
ending = ['les','sco', 'igo']
Expected result should looks like this:
city population flag
New York 8.5 N
Los Angeles 3.9 Y
Buffalo 0.25 N
Miami 0.45 N
San Deigo 1.4 Y
San Francisco 0.87 Y
I tried to use if statement:
if df['city'].str.endswith(tuple(ending)):
val = 'Y'
elif df['city'].str.endswith(tuple(ending)):
val= 'Y'
else:
val = 'N'
I get error message:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Any suggestion? Thank!
Using str.endswith
, this dose not required the same length string in ending
df.city.str.endswith(tuple(ending)).map({True:'Y',False:'N'})
0 N
1 Y
2 N
3 N
4 Y
5 Y
Name: city, dtype: object