【问题标题】:Find closely matching value index in a Dataframe column using pandas [duplicate]使用 pandas 在 Dataframe 列中查找紧密匹配的值索引 [重复]
【发布时间】:2019-08-16 18:56:37
【问题描述】:

我有浮点数的数据框。我想找到紧密匹配的数字索引。

df = 
index    value
0          10.53
1          20.23
2          12.34          
3          34.12
4          5.67
5          19.56

我想找到与 9.5 最匹配的值索引

matc_idx = df['value'].index.get_loc(9.5)

输出:

KeyError:

如何找到紧密匹配的索引。在这种情况下,我期待

print(matc_idx) 
0

以前接受的答案使用了已折旧的ix

【问题讨论】:

  • df.iloc[(df['value']-9.5).abs().argsort()[:1]].index 来自这个thread
  • @politicalscientist 我试过你的方法,得到以下回复AttributeError: 'DataFrame' object has no attribute 'argsort'
  • 对不起,如果我错过了什么。我复制了你的 df 并运行了上述代码,它按预期工作,所以不确定是什么问题:(
  • df['value'].sub(9.5).abs().sort_values().index[0]df['value'].sub(9.5).abs().idxmin()

标签: python pandas


【解决方案1】:

使用idxmin 获取最接近的euclidean distance

VAL = 9.5
((df['value'] - VAL)**2).idxmin()

输出

 0

【讨论】:

  • 你的方法奏效了。
  • 不确定为什么需要欧几里得距离。当然,绝对差异就足够了。无论如何,idxmin 在任何一种情况下都可以正常工作。
  • @Alexander 表示 1D,绝对差异是欧几里得;p 我刚刚提到了 R^N 解决方案的欧几里得 - 当然我在这里省略了 sqrt 以避免冗余
猜你喜欢
  • 2018-03-19
  • 1970-01-01
  • 2014-11-26
  • 2016-10-06
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 2017-12-31
  • 1970-01-01
相关资源
最近更新 更多