1

I would like to change the column days (which is a datetime column) conditional on the indicator column, i.e. when indicator is equal to either DTM or AMC, I would like to add 1 day to the days column.

 import pandas as pd
 df = pd.DataFrame({'days': [1, 2, 3],
            'indicator': ['BMO', 'DTM','AMC']})

So the result looks like this:

   days indicator
0     1       BMO
1     3       DTM
2     4       AMC

3 Answers 3

1

Use np.where with isin:

df['days'] = np.where(df['indicator'].isin(['DTM', 'AMC']), df['days'].add(1), df['days'])

   days indicator
0     1       BMO
1     3       DTM
2     4       AMC
Sign up to request clarification or add additional context in comments.

Comments

1

Use a boolean mask:

df['days'] += (df.indicator.eq('AMC') | df.indicator.eq('DTM'))
print(df)

Output

   days indicator
0     1       BMO
1     3       DTM
2     4       AMC

As an alternative you could use isin:

df['days'] += df.indicator.isin(('AMC', 'DTM'))
print(df)

You can add the boolean mask directly because in Python, booleans values are integers (0, 1).

Comments

1

Use Series.mask:

df['days']=df['days'].mask(df['indicator'].isin(['DTM','AMC']),df['days']+1)

or Series.where:

df['days']=df['days'].where(~df['indicator'].isin(['DTM','AMC']),df['days']+1)

Output

#print(df)

   days indicator
0     1       BMO
1     3       DTM
2     4       AMC

1 Comment

Also, very useful, adding this to my cheat list, thanks!!

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.