Reputation: 125
I have a NumPy array sc of shape (n, n, n).
I want to store the values of
sc[i][j][l]
for 0 <= i < j < n (which means that I forget the values of the arrays for which i >= j)
and every 0 <= l < n
in a 1-dimensional np.array of size m * n where m = n(n-1)/2.
Here my function:
def fromScToMt(sc):
n = sc.shape[0]
mt = [] # start with an empty python list
for i in range(0, n - 1):
for j in range(i + 1, n):
for l in range(0, n):
mt.append(sc[i][j][l]) # populate the list with the desired values
return np.array(mt) # turn the list into a 1-dimensional numpy array
What is the most efficient way for doing this?
Thanks! Julien
Upvotes: 2
Views: 49
Reputation: 36765
You can use np.triu_indices()
to efficiently get the indices of the upper triangle:
fromScToMt(sc)
# array([ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31, 44, 45, 46, 47])
sc[np.triu_indices(n, k=1)].ravel()
# array([ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31, 44, 45, 46, 47])
Upvotes: 2