I'm wondering if there's an efficient way to get X number of rows below and above a subset of rows. I've created a basic implementation below, but I'm sure there's a better way. The subset that I care about is buyindex, which is the indices of rows that have the buy signal. I want to get several rows above and below the sellindex to verify that my algorithm is working correctly. How do I do it in an efficient way? My way seems roundabout.
buyindex = list(data2[data2['buy'] == True].index)
print buyindex [71, 102, 103, 179, 505, 506, 607]
buyindex1 = map(lambda x: x + 1, buyindex)
buyindex2 = map(lambda x: x - 1, buyindex)
buyindex3 = map(lambda x: x - 2, buyindex)
buyindex4 = map(lambda x: x + 2, buyindex)
buyindex.extend(buyindex1)
buyindex.extend(buyindex2)
buyindex.extend(buyindex3)
buyindex.extend(buyindex4)
buyindex.sort()
data2.iloc[buyindex]
UPDATE - this is the structure of the data. I have the indices of the "buys." but I basically want to get several indices above and below the buys.
VTI upper lower sell buy AboveUpper BelowLower date tokens_left
38 61.25 64.104107 61.341893 False True False True 2007-02-28 00:00:00 5
39 61.08 64.218341 61.109659 False True False True 2007-03-01 00:00:00 5
40 60.21 64.446719 60.640281 False True False True 2007-03-02 00:00:00 5
41 59.51 64.717936 60.050064 False True False True 2007-03-05 00:00:00 5
142 63.27 68.909776 64.310224 False True False True 2007-07-27 00:00:00 5
217 62.98 68.858308 63.587692 False True False True 2007-11-12 00:00:00 5
254 61.90 66.941126 61.944874 False True False True 2008-01-07 00:00:00 5
255 60.79 67.049925 61.312075 False True False True 2008-01-08 00:00:00 5
296 57.02 61.382677 57.371323 False True False True 2008-03-07 00:00:00 5
297 56.15 61.709166 56.788834 False True False True 2008-03-10 00:00:00 5
UPDATE: I created a general function based off the chosen answer. Let me know if you think this could be made even more efficient.
def get_test_index(df, column, numbers):
"""
builds an test index based on a range of numbers above and below the a specific index you want.
df = dataframe to build off of
column = the column that is important to you. for instance, 'buy', or 'sell'
numbers = how many above and below you want of the important index
"""
idx_l = list(df[df[column] == True].index)
for i in range(numbers)[1:]:
idxpos = data2[column].shift(i).fillna(False)
idxpos = list(df[idxpos].index)
idx_l.extend(idxpos)
idxneg = data2[column].shift(-i).fillna(False)
idxneg = list(df[idxneg].index)
idx_l.extend(idxneg)
#print idx_l
return sorted(idx_l)