我有一个 DataFrame
并尝试选择一行(给定特定索引)及其前面的 n
行。
我尝试过类似的方法:
last_10 = self.market_data.iloc[index:-10]
但这似乎给出了从索引
到数据帧末尾减去10行的所有内容。
我希望返回由 index
指定的行及其前面的 10 行
最佳答案
如果像 DatetimeIndex
这样的通用索引使用 DataFrame.iloc
与 Index.get_loc
对于 val
的位置:
print (market_data)
val
Date
1900-01-01 2.0
1900-01-02 3.0
1900-01-03 5.1
1900-01-04 5.0
1900-01-05 6.0
1900-01-06 7.0
1900-01-07 3.0
n = 3
val = '1900-01-04'
pos = market_data.index.get_loc(val)
last_10 = market_data.iloc[pos-n+1:pos+1]
print (last_10)
val
Date
1900-01-02 3.0
1900-01-03 5.1
1900-01-04 5.0
如果 RangeIndex
- 在索引 4
之前获取 3 个值,则使用 DataFrame.loc
:
print (market_data)
Date val
0 1900-01-01 2.0
1 1900-01-02 3.0
2 1900-01-03 5.1
3 1900-01-04 5.0
4 1900-01-05 6.0
5 1900-01-06 7.0
6 1900-01-07 3.0
n = 3
val = 4
last_10 = market_data.loc[val-n+1:val]
print (last_10)
Date val
2 1900-01-03 5.1
3 1900-01-04 5.0
4 1900-01-05 6.0
关于python - 如何选择 DataFrame 中索引行之前的 n 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55433251/