Niccola Tartaglia
Niccola Tartaglia

Reputation: 1667

Conditional Change in Pandas Dataframe

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

Upvotes: 1

Views: 91

Answers (3)

ansev
ansev

Reputation: 30920

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

Upvotes: 1

Dani Mesejo
Dani Mesejo

Reputation: 61900

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).

Upvotes: 1

Erfan
Erfan

Reputation: 42886

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

Upvotes: 1

Related Questions