假设我有一个带有分类变量和值的时间序列数据帧:
In [4]: df = pd.DataFrame(data={'category': np.random.choice(['A', 'B', 'C', 'D'], 11), 'value': np.random.rand(11)}, index=pd.date_range('2015-04-20','2015-04-30'))
In [5]: df
Out[5]:
category value
2015-04-20 D 0.220804
2015-04-21 A 0.992445
2015-04-22 A 0.743648
2015-04-23 B 0.337535
2015-04-24 B 0.747340
2015-04-25 B 0.839823
2015-04-26 D 0.292628
2015-04-27 D 0.906340
2015-04-28 B 0.244044
2015-04-29 A 0.070764
2015-04-30 D 0.132221
如果我对类别为A的行感兴趣,过滤以隔离它们是微不足道的。但是如果我对 类别A之前的n行 感兴趣呢?如果n = 2,我希望看到类似的东西:
In [5]: df[some boolean indexing]
Out[5]:
category value
2015-04-20 D 0.220804
2015-04-21 A 0.992445
2015-04-22 A 0.743648
2015-04-27 D 0.906340
2015-04-28 B 0.244044
2015-04-29 A 0.070764
同样,如果我对n行 类别A感兴趣怎么办?再次,如果n = 2,我想看到这个:
In [5]: df[some other boolean indexing]
Out[5]:
category value
2015-04-20 D 0.220804
2015-04-21 A 0.992445
2015-04-22 A 0.743648
2015-04-23 B 0.337535
2015-04-24 B 0.747340
2015-04-27 D 0.906340
2015-04-28 B 0.244044
2015-04-29 A 0.070764
2015-04-30 D 0.132221
谢谢!
答案 0 :(得分:4)
回答你的第一个问题:
df[pd.concat([df.category.shift(-i)=='A' for i in range(n)], axis=1).any(axis=1)]
您希望能够扩展相同(可能有点笨拙)的方法来覆盖更多案例。
答案 1 :(得分:3)
类别A的
n
行:
In [223]: idx = df.index.get_indexer_for(df[df.category=='A'].index)
In [224]: n = 1
In [225]: df.iloc[np.unique(np.concatenate([np.arange(max(i-n,0), min(i+n+1, len(df)))
for i in idx]))]
Out[225]:
category value
2015-04-20 D 0.220804
2015-04-21 A 0.992445
2015-04-22 A 0.743648
2015-04-23 B 0.337535
2015-04-28 B 0.244044
2015-04-29 A 0.070764
2015-04-30 D 0.132221
In [226]: n = 2
In [227]: df.iloc[np.unique(np.concatenate([np.arange(max(i-n,0), min(i+n+1, len(df)))
for i in idx]))]
Out[227]:
category value
2015-04-20 D 0.220804
2015-04-21 A 0.992445
2015-04-22 A 0.743648
2015-04-23 B 0.337535
2015-04-24 B 0.747340
2015-04-27 D 0.906340
2015-04-28 B 0.244044
2015-04-29 A 0.070764
2015-04-30 D 0.132221