【问题标题】:Query approximate in python dataframe? [closed]在 python 数据框中查询近似值? [关闭]
【发布时间】:2020-11-29 15:19:30
【问题描述】:

有没有办法在 python 数据帧中查询近似值?
所以对于这个例子,我可能对Y 列中的值感兴趣,该值最接近X 列中的2 应该给我“f”和/或“w”。 请看下面的例子:

df = pd.DataFrame({  
'X': [1,3,4,6,8,12,15,23,22,32],  
'Y': ['f', 'w', 'fsssa', 'ddf', 'wq', 'h', 'wss', 'rrh', 'ddw', 'e4']
})

【问题讨论】:

  • 查询范围也很有帮助!
  • 我投票重新提出这个问题,因为我想我知道这个问题的意图是什么,并且已经尝试过让这个问题更清楚。

标签: python dataframe jupyter-notebook


【解决方案1】:

您可以通过以下两个步骤完成此操作:

query_value=2 # the value, you want to query for
# calculate the absolute distance to the query value
ser_abs= (df['X']-query_value).abs()
# filter the rows for the rows with the minimum distance
df[ser_abs == ser_abs.min()]

计算结果为:

   X  Y
0  1  f
1  3  w

如果您只对 Y 值感兴趣,最后一行是:

df.loc[ser_abs == ser_abs.min(), 'Y']

【讨论】:

    猜你喜欢
    • 2016-10-11
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    相关资源
    最近更新 更多