python - how to get the datetimes before and after some specific dates in Pandas? -
i have pandas dataframe looks like
col1 2015-02-02 2015-04-05 2016-07-02
i add, each date in col 1, x
days before , x
days after date.
that means resulting dataframe contain more rows (specifically, n(1+ 2*x), n orignal number of dates in col1
)
how can in proper pandonic way?
output (for x=1
)
col1 2015-01-01 2015-01-02 2015-01-03 2015-04-04 etc
thanks!
you can way, i'm not sure it's best / fastest way it:
in [143]: df out[143]: col1 0 2015-02-02 1 2015-04-05 2 2016-07-02 in [144]: %paste n = 2 (df.col1.apply(lambda x: pd.series(pd.date_range(x - pd.timedelta(days=n), x + pd.timedelta(days=n)) ) ) .stack() .drop_duplicates() .reset_index(level=[0,1], drop=true) .to_frame(name='col1') ) ## -- end pasted text -- out[144]: col1 0 2015-01-31 1 2015-02-01 2 2015-02-02 3 2015-02-03 4 2015-02-04 5 2015-04-03 6 2015-04-04 7 2015-04-05 8 2015-04-06 9 2015-04-07 10 2016-06-30 11 2016-07-01 12 2016-07-02 13 2016-07-03 14 2016-07-04
Comments
Post a Comment