【问题标题】:Python: Distance to nearest neighbor in row of DataFrame [closed]Python:到DataFrame行中最近邻居的距离[关闭]
【发布时间】:2022-01-08 08:16:37
【问题描述】:

我有一个如下所示的数据框:

d = {'col1': [1, 2], 'col2': [3, 4], 'col3': [4, 10], 'col4': [1, 8]}
df = pd.DataFrame(data=d)
df:
      col1 col2 col3 col4
   0  1    3    4    1
   1  2    4    10   8

如何找到每列每行中最近邻的距离?即 df[col1][0] 的最近邻居的距离为 0,因为从 1 到 1 的距离(df[col1][0] = 1 和 df[col4][0] = 1)为 0

【问题讨论】:

  • 您的预期输出是什么?你尝试过什么?

标签: python pandas dataframe distance nearest-neighbor


【解决方案1】:

IIUC,试试吧:

>>> df.apply(lambda x: df.drop(x.name, axis=1).subtract(x, 0).abs().min(1))

   col1  col2  col3  col4
0     0     1     1     0
1     2     2     2     2

【讨论】:

    猜你喜欢
    • 2019-06-30
    • 2011-11-12
    • 2019-06-05
    • 2017-06-25
    • 2021-07-25
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 2021-07-05
    相关资源
    最近更新 更多