python pandas - 根据包含字符串列表的列B更改A列中的值

时间:2017-08-14 12:03:55

标签: python list pandas dataframe

如何更改"喜剧"中的值?列基于对应的"类型"列值(列表)包含"喜剧"?

" Comedy"的结果列应

<td th:text="*{#temporals.format(thedate, 'yyyy-MM-dd HH:mm:ss')}">

我已尝试过.isin,.contains,.find等所有内容。

注意:最初是&#34;类型中的值&#34;列看起来像

True
False
True
True
True

但我使用

拆分它们
Adventure|Animation|Children|Comedy|Fantasy

dataframe example

2 个答案:

答案 0 :(得分:3)

如果in列有apply,请使用list参数替换NaN添加fillna

df["genres"] = df.genres.str.split("|")
df['new'] = df['genres'].fillna('').apply(lambda x: 'Comedy' in x)
print (df)
                                              genres    new
0  [Adventure, Animation, Children, Comedy, Fantasy]   True
1                     [Adventure, Children, Fantasy]  False
2                                  [Comedy, Romance]   True
3                           [Comedy, Drama, Romance]   True
4                                           [Comedy]   True
5                                                NaN  False

感谢John Galt寻求解决方案:

df['new'] = ['Comedy' in x for x in df['genres']]

没有list使用contains参数na=False

df['new'] = df['genres'].str.contains('Comedy', na=False)
print (df)
                                        genres    new
0  Adventure|Animation|Children|Comedy|Fantasy   True
1                   Adventure|Children|Fantasy  False
2                               Comedy|Romance   True
3                         Comedy|Drama|Romance   True
4                                       Comedy   True
5                                          NaN  False

答案 1 :(得分:3)

试试这个:

In [97]: df
Out[97]:
                           genres
0  [Adventure, Animation, Comedy]
1               [Fantasy, Horror]
2                 [Comedy, Drama]
3                           [nan]
4                             NaN

In [98]: df['Comedy'] = df.genres.fillna('').apply(lambda x: len(set(x) & set(['Comedy'])) == 1)

In [99]: df
Out[99]:
                           genres  Comedy
0  [Adventure, Animation, Comedy]    True
1               [Fantasy, Horror]   False
2                 [Comedy, Drama]    True
3                           [nan]   False
4                             NaN   False
相关问题