【问题标题】:Check whether the two string columns contain each other in Python在 Python 中检查两个字符串列是否相互包含
【发布时间】:2021-10-07 11:12:26
【问题描述】:

给定一个小数据集如下:

   id       a       b
0   1     lol   lolec
1   2   rambo     ram
2   3      ki     pio
3   4    iloc     loc
4   5   strip  rstrip
5   6  lambda  lambda

我想根据以下条件创建一个新列c

如果a 等于或b 的子字符串或反之亦然,则创建一个值为1 的新列c,否则保留它作为0

我如何在 Pandas 或 Python 中做到这一点?

预期结果:

   id       a       b  c
0   1     lol   lolec  1
1   2   rambo     ram  1
2   3      ki     pio  0
3   4    iloc     loc  1
4   5   strip  rstrip  1
5   6  lambda  lambda  1

要检查a是否在bb是否在a中,我们可以使用:

df.apply(lambda x: x.a in x.b, axis=1)
df.apply(lambda x: x.b in x.a, axis=1)

【问题讨论】:

    标签: python-3.x pandas string dataframe


    【解决方案1】:

    使用zip 和列表理解:

    df['c'] = [int(a in b or b in a) for a, b in zip(df.a, df.b)]
    
    df
       id       a       b  c
    0   1     lol   lolec  1
    1   2   rambo     ram  1
    2   3      ki     pio  0
    3   4    iloc     loc  1
    4   5   strip  rstrip  1
    5   6  lambda  lambda  1
    

    或者使用apply,只需将这两个条件与or结合起来:

    df['c'] = df.apply(lambda r: int(r.a in r.b or r.b in r.a), axis=1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 2012-11-16
      • 2021-01-21
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多