Mamed
Mamed

Reputation: 772

For loop to iterate the operation

import numpy as np
import pandas as pd
from scipy.spatial.distance import directed_hausdorff

df:

1       1.1     2       2.1     3       3.1     4       4.1

45.13   7.98    45.10   7.75    45.16   7.73    NaN     NaN
45.35   7.29    45.05   7.68    45.03   7.96    45.05   7.65

Calculated distance for 1 couple

x = df['3']
y = df['3.1']
P = np.array([x, y])

q = df['4']
w = df['4.1']
Q = np.array([q, w])

Q_final = list(zip(Q[0], Q[1]))
P_final = list(zip(P[0], P[1]))

directed_hausdorff(P_final, Q_final)[0]

Desired output:

Same process with for loop for the whole dataset

distance from a['0'], a['0']is 0
from a['0'], a['1'] is 0.234 (some number)
from a['0'], a['2'] is .. ...

From [0] to all, then to [1] to all and etc. Finally I should get a matrix with 0s` in diagonal

I Have tried:

space = list(df.index)

dist = []
for j in space:
    for k in space:
         if k != j:
             dist.append((j, k, directed_hausdorff(P_final, Q_final)[0]))

But getting same value of distance between [3] and [4]

Upvotes: 0

Views: 99

Answers (1)

Anna Nevison
Anna Nevison

Reputation: 2759

I am not entirely sure what you are trying to do.. but based on how you calculated the first one, here is a possible solution:

import pandas as pd
import numpy as np
from scipy.spatial.distance import directed_hausdorff

df = pd.read_csv('something.csv')

groupby = lambda l, n: [tuple(l[i:i+n]) for i in range(0, len(l), n)]
values = groupby(df.columns.values, 2)

matrix = np.zeros((4, 4))

for Ps in values:
    x = df[str(Ps[0])]
    y = df[str(Ps[1])]
    P = np.array([x, y])
    for Qs in values:
        q = df[str(Qs[0])]
        w = df[str(Qs[1])]
        Q = np.array([q, w])
        Q_final = list(zip(Q[0], Q[1]))
        P_final = list(zip(P[0], P[1]))
        matrix[values.index(Ps), values.index(Qs)] = directed_hausdorff(P_final, Q_final)[0]
print(matrix)

Output:

[[0.         0.49203658 0.47927028 0.46861498]
 [0.31048349 0.         0.12083046 0.1118034 ]
 [0.25179357 0.22135944 0.         0.31064449]
 [0.33955854 0.03       0.13601471 0.        ]]

Upvotes: 1

Related Questions