python - 获取 DataFrame 中的上一个和下一个索引值(如果它们存在)

标签 python pandas dataframe

假设我有一个 DataFrame

df = pd.DataFrame(dict(vals=np.random.randint(0, 10, 10)),
                  index=pd.date_range('20170401', '20170410'))

>>> df
               vals
2017-04-01     9
2017-04-02     8
2017-04-03     4
2017-04-04     5
2017-04-05     9
2017-04-06     9
2017-04-07     5
2017-04-08     3
2017-04-09     3
2017-04-10     1

还有一个我知道在我的索引中但不知道位置的特定日期,例如

cur_dt = df.index[np.random.randint(0, df.index.size)]

>>> cur_dt
Timestamp('2017-04-05 00:00:00', freq='D')

给定 cur_dt,我想确定索引中的上一个和下一个值是什么。如果 cur_dt 是我索引中的第一个(最后一个)值,那么前一个(下一个)元素应该是 cur_dt 本身。

回顾一下,我的问题是,在给定我的当前值的情况下,在我的索引中查找上一个和下一个值(或者我的当前值本身,如果它是端点)的最简单方法是什么?


我目前的做法似乎比较迂回,这也是我提问的动机。

cur_iloc = df.index.get_loc(cur_dt)
prev = cur_dt if cur_iloc == 0 else df.index[cur_iloc-1]
next = cur_dt if cur_iloc == df.index.size-1 else df.index[cur_iloc+1]

>>> prev
Timestamp('2017-04-04 00:00:00', freq='D')
>>> next
Timestamp('2017-04-06 00:00:00', freq='D')

如果没有更直接的方式,那么我深表歉意。我想象能够将我的索引从我的当前值向前和向后“移动”一次(对端点进行一些很好的处理),但我不确定这是否可能。

最佳答案

假设索引已排序,尝试使用numpy.searchsorted :

源数据集:

In [185]: df
Out[185]:
            vals
2017-04-01     5
2017-04-02     3
2017-04-03     9
2017-04-04     8
2017-04-05     1
2017-04-06     0
2017-04-07     4
2017-04-08     5
2017-04-09     1
2017-04-10     8

In [186]: cur_dt
Out[186]: Timestamp('2017-04-02 00:00:00', freq='D')

解决方案:

In [187]: idx = np.searchsorted(df.index, cur_dt)

In [188]: df.index[max(0, idx-1)]
Out[188]: Timestamp('2017-04-01 00:00:00', freq='D')

In [189]: df.index[min(idx+1, len(df)-1)]
Out[189]: Timestamp('2017-04-03 00:00:00', freq='D')

关于python - 获取 DataFrame 中的上一个和下一个索引值(如果它们存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43482549/

相关文章:

python - python中的复数

python - 在 Python 中合并两个列表

python - 我在 google colab 上训练了一个 keras 模型。现在无法将其加载到我的系统本地。

python - pandas 中的 groupby 具有必须保持状态的功能

python - 动态添加行到 DataFrame

python - 如何在Python中实现非阻塞无限循环

python - 如何使用 python Pandas 减去行?

python - 显示更多有效数字的系数

用于数据分析的 Lua 库(数据框)

python - 根据多行条件比较两个不同的数据帧