How to make array into array list in python -
from array
s = np.array([[35788, 41715, ... 34964], [5047, 23529, ... 5165], [12104, 33899, ... 11914], [3646, 21031, ... 3814], [8704, 7906, ... 8705]])
i have loop this
end =[] in range(len(s)): j in range(i, len(s)): out = mahalanobis(s[i], s[j], invcov) end.append(out) print end
and take output :
[0.0, 12.99, 5.85, 10.22, 3.95, 0.0, 5.12, 3.45, 4.10, 0.0, 5.05, 8.10, 0.0, 15.45, 0.0]
but want output :
[[0.0, 12.99, 5.85, 10.22, 3.95], [12.99, 0.0, 5.12, 3.45, 4.10], [5.85, 5.12, 0.0, 5.05, 8.10], [10.22, 3.45, 5.05, 0.0, 15.45], [3.95, 4.10, 8.10, 15.45, 0.0]]
given list,
end = [0.0, 12.99, 5.85, 10.22, 3.95, 0.0, 5.12, 3.45, 4.10, 0.0, 5.05, 8.10, 0.0, 15.45, 0.0]
you build desired 2-dimensional array using
import numpy np result = np.zeros((s.shape[0],)*2) # 1 result[np.triu_indices(s.shape[0], 0)] = end # 2 result += result.t # 3 print(result)
which yields
[[ 0. 12.99 5.85 10.22 3.95] [ 12.99 0. 5.12 3.45 4.1 ] [ 5.85 5.12 0. 5.05 8.1 ] [ 10.22 3.45 5.05 0. 15.45] [ 3.95 4.1 8.1 15.45 0. ]]
- make array filled zeros
np.triu_indices(s.shape[0], 0)
returns indices upper-triangle of array of shape(s.shape[0], s.shape[0])
.in [95]: np.triu_indices(5, 0) out[95]: (array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4]), array([0, 1, 2, 3, 4, 1, 2, 3, 4, 2, 3, 4, 3, 4, 4]))
result[...] = end
fills upper-triangle valuesend
.take transpose of
result
, addresult
, makingresult
symmetric.
this allows obtain result without calling both mahalanobis(s[i], s[j])
, mahalanobis(s[j], s[i])
unnecessary since mahalanbis
distance symmetric.
note diagonal 0 since mahalanobis(x,x)
equals 0 x
. little added efficiency, exclude diagonal:
end =[] in range(len(s)): j in range(i+1, len(s)): # <-- note i+1 out = mahalanobis(s[i], s[j], invcov) end.append(out)
and build result
same code before except can use
result[np.triu_indices(s.shape[0], 1)] = end
instead of
result[np.triu_indices(s.shape[0], 0)] = end
the second argument np.triu_indices
controls diagonal offset. when offset 1, indices corresponding the main diagonal omitted.
in [96]: np.triu_indices(5, 1) out[96]: (array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3]), array([1, 2, 3, 4, 2, 3, 4, 3, 4, 4]))
Comments
Post a Comment