【问题标题】:How to update value of column B if column A contains some specific string or set of words out of sentence in column A如果 A 列在 A 列中包含某些特定字符串或句子外的单词集,如何更新 B 列的值
【发布时间】:2019-11-17 14:11:20
【问题描述】:

如果 A 列有句子:hb_mumbai 炼油厂数据。所以我需要检查 A 列是否包含 hb_mumbai,然后将 B 列的值更新为:hb_mumbai

我尝试使用 contains 函数来实现它,但它没有产生所需的输出。

if df['A'].str.contains('hb_mumbai'): 
    df['B']=='hb_mumbai'

实际结果:B 列的值未更新 期望的结果:B 列的值应该得到更新。

【问题讨论】:

  • 你可以使用numpy.where,这样更有效,df.A = np.where(df.B.str.contains('hb_mumbai'),'hb_mumbai', df.A)。也做import numpy as np
  • 在使用 where() 时,我们可以在 contains() 函数中给出多个条件吗?

标签: python substring contains sentence


【解决方案1】:

'=='是相等运算符,不赋值,用'='代替

【讨论】:

    【解决方案2】:

    如果df 是字典,那么你可以这样做:

    if 'hb_mumbai' in df['A']:
        df['B']='hb_mumbai'
    

    如前所述,== 用于检查相等性; = 将分配一个值。

    【讨论】:

      【解决方案3】:
      import pandas as pd
      
      df = pd.DataFrame({"A":['hb_mumbai in here','asd','qwe'],
                         "B":['123','456','789'] })
      
      print(df)
      
      
      df['B'] = ['hb_mumbai' if 'hb_mumbai' in a else b for a,b in zip(df['A'],df['A'])]
      
      print(df)
      

      【讨论】:

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