How to replace a string in pandas column based on a condition?

Viewed 94

I am trying to check if values in column are numbers and replace them with other strings. I am using the code

df["recs"] = ["45", "emp1", "12", "emp3", "emp4", "emp5"]
recomm = df["recs"]
# check if the values in each row of this column a number
recomm = recomm.str.replace(recomm.isdigit(), 'Number')

But it is generating an error

AttributeError: 'Series' object has no attribute 'isdigit'
2 Answers

You could use str.replace here with the regex pattern ^\d+$:

df["recs"] = df["recs"].str.replace(r'^\d+$', 'Number')

The pattern ^\d+$ targets only string values which are pure numbers.

I'd prefer without regex and with mask:

df['recs'] = df['recs'].mask(df['recs'].str.isdigit(), 'Number')
Related