0

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.

  • u can use `numpy.where` for this which is more efficient , `df.A = np.where(df.B.str.contains('hb_mumbai'),'hb_mumbai', df.A)`. Do `import numpy as np` also. – Shijith Jul 08 '19 at 05:17
  • Possible duplicate of [How to conditionally update DataFrame column in Pandas](https://stackoverflow.com/questions/18196203/how-to-conditionally-update-dataframe-column-in-pandas) –  Jul 08 '19 at 05:18
  • while using where() can we give more than one condition in contains() function? – Manjinder Singh Jul 08 '19 at 10:24

3 Answers3

2

'=='is equality operator, not assigning values, use '=' instead

0

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.

l'L'l
  • 44,951
  • 10
  • 95
  • 146
0
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)
Daniel Fischer
  • 947
  • 6
  • 8