Pandas iloc 返回 n 行,如果 n 大于 len 则返回 0
Pandas iloc go back n rows and if n is larger than len go back to 0
假设我有一个看起来像这样的系列:
myseries = ['a', 'b', 'c', 'd', 'e', 'f']
series = pd.Series(myseries)
+---+---+
| 0 | a |
| 1 | b |
| 2 | c |
| 3 | d |
| 4 | e |
| 5 | f |
+---+---+
然后我做了一些基本的过滤,并希望像这样获得前 n=2 行:
idx = series.index[3]
series.iloc[idx-n: idx]
1 b
2 c
dtype: object
但是如果我让 n 太大,比如 n=5,我会返回一个空系列
Series([], dtype: object)
如果我的 n 太大,它只会停在它可以到达的最大 n(在本例中为 3),我该如何做到这一点?
我认为您需要实施手动检查,例如:
series.iloc[max(idx-n, 0):idx]
另外请注意,您使用 idx = series.index[3]
提取了 索引 ,因此您应该将其与 loc
一起使用,而不是 iloc
。
假设我有一个看起来像这样的系列:
myseries = ['a', 'b', 'c', 'd', 'e', 'f']
series = pd.Series(myseries)
+---+---+
| 0 | a |
| 1 | b |
| 2 | c |
| 3 | d |
| 4 | e |
| 5 | f |
+---+---+
然后我做了一些基本的过滤,并希望像这样获得前 n=2 行:
idx = series.index[3]
series.iloc[idx-n: idx]
1 b
2 c
dtype: object
但是如果我让 n 太大,比如 n=5,我会返回一个空系列
Series([], dtype: object)
如果我的 n 太大,它只会停在它可以到达的最大 n(在本例中为 3),我该如何做到这一点?
我认为您需要实施手动检查,例如:
series.iloc[max(idx-n, 0):idx]
另外请注意,您使用 idx = series.index[3]
提取了 索引 ,因此您应该将其与 loc
一起使用,而不是 iloc
。