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
Post a Comment for "How To Update Another Column Based On Regex Match In A Different Column In Python 3.x?"