繁体   English   中英

用“真”找到最近的索引并计算距离(熊猫)

[英]Find the closest index with "True" and calculating the distance (Pandas)

我有一个这样的数据框:

编号 变量1 变量2 变量 3
0 真的 错误的 错误的
1 错误的 真的 错误的
2 真的 错误的 真的
3 错误的 错误的 错误的
4 真的 错误的 真的

我想创建三个新列,其距离(距每一行)最近的 True,如果该行的 True 显示为 0,那么我会得到这个:

编号 变量1 变量2 变量 3 distV1 distV2 分配V3
0 真的 错误的 错误的 0 1 2
1 错误的 真的 错误的 1 0 1
2 真的 错误的 真的 0 1 0
3 错误的 错误的 错误的 1 2 1
4 真的 错误的 真的 0 3 0

我已阅读与此主题相关的所有其他讨论,但无法找到此类问题的答案。

代码

填充到列中最近的True位置的距离。

from scipy.spatial import KDTree
    
array = df.to_numpy()
bmp = array.astype(np.uint8)
distance = []
for points in bmp.T:
    all_points = np.argwhere(points!=2)
    true_points = np.argwhere(points==1)
    tree = KDTree(true_points)
    dist = tree.query(all_points, k=1, p=2)[0]
    distance.append(dist)
distance = np.array(distance).astype(int).T
df[df.columns + "_dist"] = distance

输出

      Var1   Var2   Var3  Var1_dist  Var2_dist  Var3_dist
idx                                                      
0     True  False  False          0          1          2
1    False   True  False          1          0          1
2     True  False   True          0          1          0
3    False  False  False          1          2          1
4     True  False   True          0          3          0

填充到整个表格中最近的True位置的距离。

from scipy.spatial import KDTree

array = df.to_numpy()
bmp = array.astype(np.uint8)
all_points = np.argwhere(bmp!=2)
true_points = np.argwhere(bmp==1)
tree = KDTree(true_points)
distance = tree.query(all_points, k=1, p=1)[0]
distance.resize(array.shape)
df[df.columns + "_dist"] = distance.astype(int)

输出

      Var1   Var2   Var3  Var1_dist  Var2_dist  Var3_dist
idx                                                      
0     True  False  False          0          1          2
1    False   True  False          1          0          1
2     True  False   True          0          1          0
3    False  False  False          1          2          1
4     True  False   True          0          1          0

解释

  1. 使用np.array制作0,1数据
array([[1, 0, 0],
       [0, 1, 0],
       [1, 0, 1],
       [0, 0, 0],
       [1, 0, 1]], dtype=uint8)
  1. argwhere将返回符合条件的点的位置坐标。

  2. KDTree是一种寻找最近点的经典算法。

    1. arg k表示前 n 个最近点

    2. arg p =1 表示“曼哈顿”距离

    使用哪个 Minkowski p 范数。

    1 是绝对值之和距离(“曼哈顿”距离)。

    2 是通常的欧几里得距离。

参考

scipy.KDTree

这是使用 numpy 操作的一种方法:

for c in df:
    r = np.where(df[c])[0]
    d = abs(df.index.values[:, None] - r)
    df[f'{c}_dist'] = abs(df.index - r[d.argmin(1)])

print(df)

    Var1   Var2   Var3  Var1_dist  Var2_dist  Var3_dist
0   True  False  False          0          1          2
1  False   True  False          1          0          1
2   True  False   True          0          1          0
3  False  False  False          1          2          1
4   True  False   True          0          3          0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM