简体   繁体   English

从一个(n,n,n)NumPy数组到特定的一维提取

[英]From an (n, n, n) NumPy array to a specific 1-dimensional extraction

I have a NumPy array sc of shape (n, n, n).我有一个形状为(n,n,n)的 NumPy 数组 sc。

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.我想为 0 <= i < j < n 存储sc[i][j][l]的值(这意味着我忘记了 i >= j 的 arrays 的值)和每个 0 <= l < n 在大小为 m * n 的一维 np.array 中,其中 m = n(n-1)/2。

Here my function:这是我的 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朱利安

You can use np.triu_indices() to efficiently get the indices of the upper triangle:您可以使用np.triu_indices()有效地获取上三角形的索引:

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])

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

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