muon muon - 3 months ago 16
Python Question

pandas shift date using values from another column

code to make test data:

import pandas as pd
df = pd.DataFrame({'A': pd.date_range(start='1-1-2016',periods=5, freq='M')})
df['B'] = df.A.dt.month
print(df)


data looks like

B A
0 1 2016-01-31
1 2 2016-02-29
2 3 2016-03-31
3 4 2016-04-30
4 5 2016-05-31


how to shift column A backwards by number of months as value from column B

to the effect of

df['A'] - pd.DateOffset(months=value_from_column_B)

Answer

You can try:

df['C'] = df[['A', 'B']].apply(lambda x: x['A'] - pd.DateOffset(months=x['B']), axis=1)