2

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

train_df.age["weeks" in train_df.age] = 0

and

for i in train_df['age']:
    if "weeks" in i:
        i = "0"

None of which seem to work.

Any advice on how to do this? Thanks.

3
  • what do you expect this to look like? Commented Jun 6, 2016 at 20:56
  • are these two separate columns? or one column with a int and str? Commented Jun 6, 2016 at 21:00
  • Are you trying to replace the strings "month" or "week" to 0, or the numbers in the same rows in the other column? Commented Jun 6, 2016 at 21:40

1 Answer 1

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
1     0
1     0
4  year
3     0
Sign up to request clarification or add additional context in comments.

4 Comments

Any idea, if this can be generalised to not just searching in the column 'age' but to replace week | month with 0 through the entire dataframe (so all columns)
@Vipluv you either stack the entire df and then unstack: stacked = train_df.stack() stacked.loc[stacked.str.contains(r'week|month'), 'age'] = 0 and then call unstack() unstack = stacked.unstack() or you can just call apply on the df to generate a boolean mask and then replace mask = df.apply(lambda x: x.str.contains(r'week|week')) and then do df[mask] = 0
the mask idea is actually working if i use lambda x: str('week') in str(x) as i have a df with mixed dtypes. otherwise with regex mask method as above i get error : nothing to repeat ... maybe i will post a dedicated question about this with full examples
I elaborated the question a bit more here stackoverflow.com/questions/50524343/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.