【问题标题】:Pandas iloc go back n rows and if n is larger than len go back to 0熊猫 iloc 返回 n 行,如果 n 大于 len 则返回 0
【发布时间】:2021-07-17 03:17:24
【问题描述】:

假设我有一个看起来像这样的系列:

myseries = ['a', 'b', 'c', 'd', 'e', 'f']
series = pd.Series(myseries)

+---+---+
| 0 | a |
| 1 | b |
| 2 | c |
| 3 | d |
| 4 | e |
| 5 | f |
+---+---+

然后我做了一些基本的过滤,并希望得到这样的 prev 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)?

【问题讨论】:

    标签: python pandas slice series


    【解决方案1】:

    我认为您需要实施手动检查,例如:

    series.iloc[max(idx-n, 0):idx]
    

    另一方面,您使用idx = series.index[3] 提取索引,因此您应该使用loc,而不是iloc

    【讨论】:

    • 哇,我什至没有想过用这种方式使用 max。谢谢!
    • 我应该使用 loc 而不是 iloc 是什么意思?我想获得 prev n 值。 iloc 不会为此工作,因为它是按顺序索引的(至少在我的用例中是这样)
    • 我的意思是idx=series.index[3] 而不是idx=3 有什么意义? series.iloc[idx] 指的是 idx-th 行,而不是 named idx 的行,就像您提取它的方式一样。
    • 啊,我明白你现在在说什么了。谢谢你的收获。我误解了 iloc 和 loc 的作用
    猜你喜欢
    • 2019-10-21
    • 2019-01-24
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    相关资源
    最近更新 更多