【问题标题】:How to find row which has the minimum overall distance from the other rows of the pandas dataframe如何找到与熊猫数据框其他行的总距离最小的行
【发布时间】:2018-01-04 03:37:41
【问题描述】:

我有 pandas dataframe 如下:

df:


Unnamed: 0   0      1      2      3      4
0 -527.0  143.0  143.0  248.0 -952.0
1 -527.0  143.0  143.0  248.0 -955.0
2 -527.0  143.0  143.0  248.0 -955.0

我使用mlpy.dtw_std 来计算行之间的距离矩阵:

dm = pdist ( df, lambda u,v: mlpy.dtw_std ( pd.Series ( u ).dropna ().values.tolist (),pd.Series ( v ).dropna ().values.tolist (), dist_only=True ) )
 distance_matrix=scipy.spatial.distance.squareform(dm)

如何找到与数据框其他成员的总距离最小的行索引(第一列 (Unnamed: 0))?

这是距离矩阵:

[[ 0.  3.  3.]
 [ 3.  0.  0.]
 [ 3.  0.  0.]]

【问题讨论】:

  • 一旦你得到每行的总距离,说你把它命名为dist,这样就可以了:df.loc[df.dist == min(df.dist)],但是我不能复制你的距离矩阵,我得到以下错误:AttributeError: 'module' object has no attribute 'dtw_std'.
  • 来自mlpy
  • 实际上,如果您分享您的dm 的样子,将会非常有帮助。这样我就不用重新计算了。
  • 不需要计算距离矩阵,如果我有一些具有最小值的行,我只想要一行作为答案
  • 我添加了 distance_matrix 值

标签: python pandas distance


【解决方案1】:

如果还没有,您可以先将距离矩阵转换为 numpy 数组,然后

df['dist'] = dm.mean(axis = 0)

将逐行平均距离保存为一列,然后

df[df.dist == min(df.dist)]

将为您提供与其他人的平均距离最小的行。要获取索引,您可以只选择第一列,如下所示:

df[df.dist == min(df.dist)].iloc[:,0]

【讨论】:

    猜你喜欢
    • 2018-03-24
    • 2011-06-04
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多