【问题标题】:Column contains column 4列包含第 4 列
【发布时间】:2019-05-23 13:40:38
【问题描述】:

我有一个数据框。我想测试 (C) 在每一行上 (B) 列中的数字是否在字符串 (A) 列中。

df = pd.DataFrame({'A': ["me 123", "me-123", "1234", "me 12", "123 me", "6 you 123-me"],
                   'B': [123,       123,      123,    123,     6,        123]})

我几乎可以用 extract 做到这一点

df['C'] = df.A.str.extract('(\d+)', expand=False).astype(float).eq(df.B,0).astype(int)

              A    B  C
0        me 123  123  1
1        me-123  123  1
2          1234  123  0
3         me 12  123  0
4        123 me    6  0
5  6 you 123-me  123  0

但是在底行因为数字 6 没有看到数字 123。我想得到

              A    B  C
0        me 123  123  1
1        me-123  123  1
2          1234  123  0
3         me 12  123  0
4        123 me    6  0
5  6 you 123-me  123  1

【问题讨论】:

    标签: pandas


    【解决方案1】:

    使用findall

    [y in x for x , y in zip(df.A.str.findall('(\d+)'),df.B.astype(str))]
    Out[733]: [True, True, False, False, False, True]
    

    【讨论】:

      【解决方案2】:

      使用Series.str.extractall 从列中获取所有数字,通过Series.unstack 重塑,检查值并添加DataFrame.any 以测试每行至少一个True

      df['C'] = (df.A.str.extractall('(\d+)')[0]
                     .unstack()
                     .astype(float)
                     .eq(df.B,0)
                     .any(axis=1)
                     .astype(int))
      print (df)
      
                    A    B  C
      0        me 123  123  1
      1        me-123  123  1
      2          1234  123  0
      3         me 12  123  0
      4        123 me    6  0
      5  6 you 123-me  123  1
      

      【讨论】:

        【解决方案3】:

        re.split

        使用“一个或多个非数字”作为模式

        import re
        
        df.assign(C=[int(str(b) in re.split('\D+', a)) for a, b in zip(df.A, df.B)])
        
                      A    B  C
        0        me 123  123  1
        1        me-123  123  1
        2          1234  123  0
        3         me 12  123  0
        4        123 me    6  0
        5  6 you 123-me  123  1
        

        【讨论】:

          猜你喜欢
          • 2019-09-22
          • 1970-01-01
          • 2023-03-09
          • 2011-02-27
          • 2016-04-15
          • 1970-01-01
          • 2021-06-04
          • 2019-07-01
          • 1970-01-01
          相关资源
          最近更新 更多