Skip to main content
 首页 » 编程设计

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

2025年05月04日22leader

如果相应的“流派”列值(列表)包含“喜剧”,我如何更改“喜剧”列中的值?

“喜剧”栏的结果应该是

True 
False 
True 
True 
True 

我已经尝试了 .isin、.contains、.find 等所有方法。

注意:最初“流派”列中的值看起来像

Adventure|Animation|Children|Comedy|Fantasy 

但我使用

拆分它们
df["genres"] = df.genres.str.split("|") 

请您参考如下方法:

试试这个:

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