向Dataframe中添加一列,该列将使用函数获取值True或False

2024-07-07 08:08:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在df中添加一列“is_戏剧”,根据内容是否属于Netflix中所列列列栏中的戏剧类别,该列的值为True或False

你能告诉我该函数是什么,以及如何将这个新列添加到我的数据帧中吗?谢谢

def drama(words):
  if 'Drama' in words:
    return 'True'
  else:
    return'False'

for i in df.listed_in:
  print(drama(i))


Tags: 数据函数infalsetrue内容dfreturn
1条回答
网友
1楼 · 发布于 2024-07-07 08:08:28

假设您有以下数据帧:

   title            listed_in
0     3%  TV Dramas, TV Shows
1   7:19               Horror
2  23:59       Dramas, Movies

然后您可以使用^{}搜索列listed_in,如果它包含单词"Drama"

df["in_drama"] = df["listed_in"].str.contains("Drama")

print(df)

印刷品:

   title            listed_in  in_drama
0     3%  TV Dramas, TV Shows      True
1   7:19               Horror     False
2  23:59       Dramas, Movies      True

编辑:使用函数(使用.apply):

def fn(x):
    return "Drama" in x


df["in_drama"] = df["listed_in"].apply(fn)

print(df)

印刷品:

   title            listed_in  in_drama
0     3%  TV Dramas, TV Shows      True
1   7:19               Horror     False
2  23:59       Dramas, Movies      True

lambda

df["in_drama"] = df["listed_in"].apply(lambda x: "Drama" in x)

相关问题 更多 >