I have a dataframe like this one:
df = pd.DataFrame(data={
'date': ['2021-01-01', '2021-01-02','2021-01-03','2021-01-04'],
'order': [False, False, True, True]
})
And I want to have a new column with the shifted date from the column with the next order = True. So the dataframe would look like this:
df_new = pd.DataFrame(data={
'date': ['2021-01-01', '2021-01-02','2021-01-03','2021-01-04'],
'order': [False, False, True, True],
'shifted_date': ['2021-01-03','2021-01-03','2021-01-04',np.nan]
})
CodePudding user response:
You can keep the True values with where
, fill backwards with bfill
, and shift
:
df['shifter_date'] = df['date'].where(df['order']).bfill().shift(-1)
output:
date order shifter_date
0 2021-01-01 False 2021-01-03
1 2021-01-02 False 2021-01-03
2 2021-01-03 True 2021-01-04
3 2021-01-04 True NaN