Home > Enterprise >  replace substrings in pandas columns while skipping rows with value: None
replace substrings in pandas columns while skipping rows with value: None

Time:10-25

I stole this from here Remove/replace columns values based on another columns using pandas

[a.replace(b,'') for a,b in zip(df1['asker'], df1['party']) if a != None]

I added if a != None because it always threw error: AttributeError: 'NoneType' object has no attribute 'replace'

Here are different solutions to the same problem: replacing substring df1['party'] within col asker

df1['new_column'] = df1['asker'].replace(to_replace=r'\b' df1['party'] r'\b', value='',regex=True)

df1['asker'] = df1.apply(lambda x: x['asker'].replace(x['party'], ''), axis = 1)

None of them worked as soon as i added the exception for None values

CodePudding user response:

Use:

[a.replace(b,'') if (a != None) or (b != None) else a for a,b in zip(df1['asker'], df1['party'])]
  • Related