简体   繁体   中英

How to update value of column B if column A contains some specific string or set of words out of sentence in column A

If column A has sentence: hb_mumbai refinery data. So i need to check if column A contains hb_mumbai then update the value of column B to : hb_mumbai

I have tried to implement it using contains function but it did not produced desired output.

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

Actual result: Value of column B is not getting updated Desired result: Value of column B should get updated.

'=='是相等运算符,不分配值,请改用'='

If df is a dictionary then you could do:

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

As mentioned == is used for checking equality; = would assign a value.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM