簡體   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