Slicing filtered DataFrame or Series(用负索引切片观察到的结果)

Slicing filtered DataFrame or Series (slicing observed results with negative index)

有一个简单的 DataFrame,我想获得一些最后的结果 - 我尝试为此使用负索引,但结果为空。

import pandas as pd
import numpy as np
dates = pd.date_range('1/1/2000', freq = '3D', periods=8)

df = pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])

print(df)
print(df.D.iloc[-1])
print(df.D.iloc[-2])
print(df.D.iloc[-1:-2])

输出:

2000-01-01 -1.174492 -1.186283 -0.514886  1.260030
2000-01-04 -0.795413 -0.389328  0.953518  1.130829
2000-01-07  0.735389  0.797403  0.240489  2.901620
2000-01-10 -0.387048  0.412311 -0.386004  0.477054
2000-01-13 -0.470163  0.519287 -0.422162 -0.383079
2000-01-16  0.249516  1.338018 -1.531770  0.816327
2000-01-19  0.367816 -0.021173  1.553473  0.267708
2000-01-22 -0.742793  1.028269 -0.306251  0.792746
0.7927456864860766
0.26770835612718263
Series([], Freq: 3D, Name: D, dtype: float64)

如您所见,负索引可以很好地获取标量值本身,但它无法对 df 系列进行切片 - 例如我只想获得 2 个最后的值。

如何使用索引或函数来实现?

如果你想对最后两个数字进行负索引,我认为你需要这样做:

df.D.iloc[-2:] 

如果你这样做df.D.iloc[-1:-2],这意味着你试图从最后一个索引开始并在第二个索引处结束(结束不包括在内);但是如果不指定步骤,它将不起作用。

例如,您可以改为:

df.D.iloc[-1:-3:-1] # to get last two value but reversed 

我犯了一个愚蠢的错误 - 我尝试使用 -1 作为切片的开始并使用 -2 作为切片的结束 :) 这是一个严重的错误 df.D.iloc[-1:-2]

所以,如果我们只使用df.D.iloc[-2:-1] or [-2:],一切都会完美无缺。感谢@ABC 的帮助