Python 熊猫在选择之前获得n个位置的索引值

Python 熊猫在选择之前获得n个位置的索引值,python,pandas,Python,Pandas,我有一个带有日期时间索引的数据帧。我也有一个特定日期的列表,我有兴趣在我的数据框中查看。我想在我的具体日期列表之前获得n行位置。比如说n=5。这是我的密码: import pandas as pd # generate an example df output = pd.DataFrame() d = pd.date_range(start='1/1/2000', end='1/1/2006', freq='D') output['Date'] = d output['Val

我有一个带有日期时间索引的数据帧。我也有一个特定日期的列表,我有兴趣在我的数据框中查看。我想在我的具体日期列表之前获得n行位置。比如说n=5。这是我的密码:

import pandas as pd     

# generate an example df
output = pd.DataFrame()    
d = pd.date_range(start='1/1/2000', end='1/1/2006', freq='D')
output['Date'] = d
output['Value'] = 1
output = output[output['Date'].dt.dayofweek < 5].reset_index(drop=True)  # remove weekends
output = output.set_index('Date')

# dates of interest
date_list = pd.to_datetime(['09/05/2002', '15/07/2004', '21/03/2005'], format='%d/%m/%Y')

# i can pull out the dates of interest, but I really want the dates '5' positions ahead
selection = output.iloc[output.index.isin(date_list)]
print(selection)
但我希望用一个矢量化的单直线来实现这一点。任何帮助都将不胜感激


非常感谢

您可以使用
flatnonzero
获取索引,将
5
添加到索引中并索引:

import numpy as np
output.iloc[np.flatnonzero(output.index[:-5].isin(date_list)) + 5]

             Value
Date             
2002-05-16      1
2004-07-22      1
2005-03-28      1

或者我们还有熊猫的
非零

output.iloc[output.index[:-5].isin(date_list).nonzero()[0]+5]

Value
Date             
2004-07-08      1
2005-03-14      1

首先获取您感兴趣日期的行位置,并按您想要的金额进行抵销。然后使用偏移行位置从数据帧中选择:

output.iloc[np.flatnonzero(output.index.isin(日期列表))+5]

如果它按日期编制索引,则应该可以:


mask = pd.DataFrame(output.index.tolist,columns = ['a']).isin(date_list)

output[mask]
如果要选择前面的5个位置,请使用

np.argwhere(np.array(mask)==True) +5

或者分割索引@jez:)很好的解决方案-以前从未遇到过“flatnonzero”!您可以将标量添加到numpy数组中,尽管这只是我的答案…-)
np.argwhere(np.array(mask)==True) +5