假设我有一个时间序列
import pandas as pd
from numpy.random import randn
dates = pd.date_range('12/31/2014', periods=10)
df = pd.DataFrame(randn(10, 4), index=dates, columns=['A', 'B', 'C', 'D'])
给定一个日期,例如 d ='1/5/2015'
我将如何选择 d 之后两天的行(天 = 1/6/2015, 1/7/2015)和d 前两天(天 = 1/4/2015, 1/3/2015)?有没有办法做到这一点来忽略周末或节假日丢失的数据?
最佳答案
你可以这样做:
from pandas.tseries.offsets import BDay
d = pd.Timestamp('1/5/2015')
two_bdays_before = d - BDay(2) # business days
two_bdays_later = d + BDay(2)
然后访问 two_bdays_before
和 two_bdays_later
之间的所有日期:
>>> df[two_bdays_before:two_bdays_later]]
A B C D
2015-01-01 0.741045 -0.051576 0.228247 -0.429165
2015-01-02 -0.312247 -0.391012 -0.256515 -0.849694
2015-01-03 -0.581522 -1.472528 0.431249 0.673033
2015-01-04 -1.408855 0.564948 1.019376 2.986657
2015-01-05 -0.566606 -0.316533 1.201412 -1.390179
2015-01-06 -0.052672 0.293277 -0.566395 -1.591686
2015-01-07 -1.669806 1.699540 0.082697 -1.229178
关于python pandas 按行数切片日期时间日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28067258/