J. Dykstra
J. Dykstra

Reputation: 211

Conditional Subtract Dates

Lets say i have the pandas dataframe below. How can i subtract one month from Var2 when Var0 is equal to b. I would like to do this conditionally, rather than creating a new data-set with just the var0 b values,subtracting and then re-merging. Var2 is in pandas datetime.

Var0    Var1    Var2
x   76.27   2018-05
x   93.38   2018-06
a   73      2018-05
a   74.33   2018-05
b   184.08  2018-03
b   184.08  2018-02
c   67.26   2018-06
c   67.18   2018-07

Upvotes: 0

Views: 137

Answers (2)

PMende
PMende

Reputation: 5460

df['Var2'] = pd.to_datetime(df['Var2'])
df['Var2'] += np.where(df['Var0'] == 'b',
                       pd.to_timedelta(1, unit='M'),
                       pd.to_timedelta(0, unit='M'))

Upvotes: 0

BENY
BENY

Reputation: 323236

Using DateOffset

df.Var2=pd.to_datetime(df.Var2,format='%Y-%m')
df.loc[df.Var0=='b','Var2']=df.Var2-pd.DateOffset(months=1)
df.Var2=df.Var2.dt.strftime('%Y-%m')
df
Out[24]: 
  Var0    Var1     Var2
0    x   76.27  2018-05
1    x   93.38  2018-06
2    a   73.00  2018-05
3    a   74.33  2018-05
4    b  184.08  2018-02
5    b  184.08  2018-01
6    c   67.26  2018-06
7    c   67.18  2018-07

Upvotes: 2

Related Questions