lundi 29 mars 2021

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?

Aucun commentaire:

Enregistrer un commentaire