代码之家  ›  专栏  ›  技术社区  ›  P. Prunesquallor

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

  •  1
  • P. Prunesquallor  · 技术社区  · 9 年前

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

    “喜剧”专栏的结果应该是

    True
    False
    True
    True
    True
    

    注意:最初“流派”列中的值如下所示

    Adventure|Animation|Children|Comedy|Fantasy
    

    但我用

    df["genres"] = df.genres.str.split("|")
    

    dataframe example

    2 回复  |  直到 9 年前
        1
  •  3
  •   MaxU - stand with Ukraine    9 年前

    试试这个:

    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
    
        2
  •  3
  •   jezrael    9 年前

    使用 in apply 如果有 list NaN s添加 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']]
    

    列表 使用 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