Skip to content Skip to sidebar Skip to footer

Pandas Replace Type Issue

I have a pandas dataframe with a row that contains data such as: 1 year 1 month 1 week 4 year 3 week etc etc I am trying to replace anything that contains 'month' or 'week' to 0 t

Solution 1:

Use str.contains:

train_df.loc[train_df['age'].str.contains(r'week|month'), 'age'] = 0

Here we pass a regex pattern that looks for whether the row contains either 'week' or 'month' and use the boolean mask to selectively update just the rows on interest:

In [4]:
df.loc[df['age'].str.contains(r'week|month'), 'age'] = 0
df

Out[4]:
    age
1  year
10104  year
30

Post a Comment for "Pandas Replace Type Issue"