我想返回"动作";在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
使用布尔索引过滤帧,并为列分配值。将startswith
和contains
中的字符串更改为所需的任何值。
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