Vance Pyton
Vance Pyton

Reputation: 174

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

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'

Upvotes: 2

Views: 578

Answers (2)

U13-Forward
U13-Forward

Reputation: 71560

I'd prefer without regex and with mask:

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

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520948

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.

Upvotes: 2

Related Questions