I have the following list:
list=[24,136,308,514,527,658,1002,1070,1560]
I have the following dataframe:
df:
co_stkdate Code ab-ret
0 1997-07-02 11 NaN
1 1997-07-04 11 NaN
2 1997-07-07 28 NaN
3 1997-07-08 28 0.002376
4 1997-07-10 30 NaN
... ... ... ... ...
5595 2002-11-13 5067 -0.001146
5596 2002-11-14 5067 0.051200
5597 2002-11-15 5121 0.092791
5598 2002-11-18 5121 0.044851
5599 2002-11-20 5121 0.035072
I want to find the rows in df
which have indexes same as the elements given in 'list'
and find 10 rows above and below those specific rows in df
for each of those rows and print them with all the column values and store them in a dictionary with co_stkdate as key. Hence I tried the following code:
values={}
for elem in list:
values = df.iloc[(elem - 10): (elem +10), elem]
But I'm getting the following error:
IndexError: single positional indexer is out-of-bounds
How can it be done? Guidance on how to remove the error will be highly appreciated.
Try this:
elm = [24,136,308,514,527,658,1002,1070,1560]
values = {}
for index in elm:
values[index] = df.loc[(list(range(index-10, index+11))),:]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.