python - 熊猫子集按最接近特定值的索引
问题描述
我想知道如何为最接近特定值的索引设置 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 。
解决方案
我找到了一个不是很整洁但可以完成工作的解决方案。
closest_to = 0
idx = abs(df.index.difference([closest_to])).min()
if idx in df.index:
pass
else:
idx = -idx
df.loc[idx]
推荐阅读
- html - 如何在打印布局和嵌入 html 文档时强制 MS Word 具有相同的布局?
- html - 结构化数据不适用于 CSS 选择器(在链接中添加斜杠和其他问题)。我该如何解决?
- pandas - 将股票图表的趋势线向右延伸
- backup - 如果没有备份,是否可以在远程 Mac 上从 Big Sur 降级到 Catalina?
- c# - C#模拟telerik ui类
- curl - 无法向 Plaid 发出 API 请求
- reactjs - 如何将 useEffect 用于没有依赖关系的 useState 变量?
- javascript - 用户从颜色输入中选择一种颜色,我需要从输入中渲染一个饼图
- bootstrap-4 - 页面滚动时如何使bootstrap 4表头粘在顶部
- maven - Jenkins 管道:如何从具有两个不同 cron 作业的单个 jenkinsfile 运行回归测试套件和冒烟测试套件