我想在 GENRE 列中返回包含特定字符串或使用熊猫以"Sp"开头的所有电影的"Action"



我想返回"动作";在GENRE数据帧/列中,包含或以";Sp";使用熊猫。

例如:

Movies    Rating   Genre
Spider    4.8      Action
Spies     2.5      Action
Special   5.0      Comedy

我尝试过"str.contains"方法,但仍然没有成功

下面的代码将返回包含"Action"的Genre和包含"Sp"作为其子字符串的Movie名称。

df.loc[(df['Movies'].str.contains('Sp')) & (df['Genre'] == 'Action')]

以下代码将返回包含"Action"的流派以及以"Sp"开头的电影名称。

df.loc[( df['Movies'].str.startswith('Sp')) & (df['Genre'] == 'Action')]

使用loc使用布尔索引过滤帧,并为列分配值。将startswithcontains中的字符串更改为所需的任何值。

df.loc[df['Movies'].str.contains('es') | df['Movies'].str.startswith('Sp'), 'Genre'] = 'Action'

我不知道这是否是一种有效的方法,但你可以做以下事情:

def filter(x,y):
if x[:2]=="Sp": return "Action"
else: return y
df["genre"]=df[["Movies", "genre"]].apply(lambda z: filter(z.Movies, z.genre), axis=1)

假设您的DataFrame(df(是:

Movies  Rating   Genre
0   Spider     4.8  Action
1    Spies     2.5  Action
2  Special     5.0  Comedy

您可以使用过滤DataFrame

import pandas as pd
df[(df.Genre == 'Action') & (df.Movies.str.startswith('Sp'))]

输出为:

Movies  Rating   Genre
0  Spider     4.8  Action
1   Spies     2.5  Action

最新更新