Skip to content Skip to sidebar Skip to footer

How To Update Another Column Based On Regex Match In A Different Column In Python 3.x?

I have a column say A with strings and another column B with binary values 1/0. I am trying to match a regular expression in column A and update column B accordingly. If this is my

Solution 1:

you can use pandas to create dataframe and make new column by checking each row data:

import pandas as pd
import re
pattern_1 = re.compile(r'\bstudent', re.IGNORECASE)
data = [['I am a teacher',0],['I am a student ',0],['Student group', 0]]

df = pd.DataFrame(data, columns =['A','B']) 
print("orginal df:",df)
df['B'] = df.apply(lambda row: 1if pattern_1.search(row.A) else row.B , axis=1)
print("\n\nmodified df:",df)

output:

orginaldf:                  AB0Iamateacher01Iamastudent02Studentgroup0modifieddf:                  AB0Iamateacher01Iamastudent12Studentgroup1

Solution 2:

You don't specify how your columns are stored, but this sounds like a job for a basic for-loop with enumerate. Assuming that A and B are lists:

for i, a_value in enumerate(A):
  B[i] = bool(pattern_1.search(A))

Post a Comment for "How To Update Another Column Based On Regex Match In A Different Column In Python 3.x?"