olive
olive

Reputation: 189

Write an if statement for a list element in Pandas dataframe cell

I have a Pandas dataframe with a column "genres" which contains a list as cell value:

import pandas
df = pd.DataFrame([
{
    "title": "The Godfather: Part II",
    "genres": ["crime", "drama"],
    "director": "Fracis Ford Coppola"
},
{
    "title": "The Dark Knight",
    "genres": ["actionmovie", "crime", "drama"],
    "director": "Christopher Nolan"
}
])

I'm trying to write an if statement to add a column "action_crime_movie" with values True or False based on matching parts of the string elements in the genres list. In other words: the 2nd line contains the word "action" (in "actionmovie") and "crime" (in "crime") so it should have the value True for "action_crime_movie".

if ("action", "crime") in df["genres"]: df["action_crime_movie"] = True
else df["action_crime_movie"] = False

However, with the above query the value was set to False...

Could anyone help me solve this issue?

Upvotes: 0

Views: 47

Answers (1)

Hamza usman ghani
Hamza usman ghani

Reputation: 2243

You can do it easily by using apply lambda

df["action_crime_movie"] = df["genres"].apply(lambda x: True if ("action" in str(x)) and ("crime" in str(x)) else False)

print(df["action_crime_movie"])
0    False
1     True
Name: action_crime_movie, dtype: bool

Upvotes: 1

Related Questions