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.

3
  • 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. Commented Jul 8, 2019 at 5:17
  • Possible duplicate of How to conditionally update DataFrame column in Pandas Commented Jul 8, 2019 at 5:18
  • while using where() can we give more than one condition in contains() function? Commented Jul 8, 2019 at 10:24

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.