首页 > 解决方案 > 熊猫子集按最接近特定值的索引

问题描述

我想知道如何为最接近特定值的索引设置 DataFrame 的子集。例如:

import pandas as pd
import numpy as np

np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)

df.index = np.random.randn(len(df.index))
closest_to = 0
df.loc[df.index.difference([closest_to]).min()]

这个子集是最远低于 0 的索引,但我正在寻找最接近零的绝对差。

编辑:当最接近的值为正时添加df.loc[abs(df.index.difference([closest_to])).min()]有效,但当负值最接近时显然会给出 KeyError 。

标签: pythonpandas

解决方案


我找到了一个不是很整洁但可以完成工作的解决方案。

closest_to = 0
idx = abs(df.index.difference([closest_to])).min()
if idx in df.index:
    pass
else:
    idx = -idx
df.loc[idx]

推荐阅读