简体   繁体   English

从 numpy 数组中提取类

[英]Extracting classes from numpy array

I am having a numpy array of data我有一个 numpy 数据数组

data = np.random.random((5, 5))

and another numpy array of equal shape masking the first one with classes from 0 to n :和另一个形状相同的 numpy 数组,用0n的类屏蔽第一个数组:

>>> mask
array([[3, 3, 1, 1, 0],
       [2, 0, 1, 2, 2],
       [0, 1, 0, 0, 3],
       [2, 1, 1, 0, 2],
       [0, 2, 3, 0, 2]])

What's the best way to compute a two-dimensional array with n rows, where each row contains all elements from data with class row_idx (described by mask )?计算具有n行的二维数组的最佳方法是什么,其中每行包含来自data的所有元素 class row_idx (由mask描述)?

You can't do it better than O(n^2) as you should iterate through all mask array.你不能比O(n^2)做得更好,因为你应该遍历所有mask数组。 As the number of elements in each class can be different the result can't be numpy array (rows have different sizes).由于每个 class 中的元素数量可能不同,因此结果不能是 numpy 数组(行具有不同的大小)。 So I don't think you can avoid python loop here with pure numpy functions.所以我认为你不能用纯 numpy 函数来避免 python 循环。 I suggest this O(n^2) solution:我建议这个O(n^2)解决方案:

ans = [[] for i in range(mask.max() + 1)]
for k, v in np.ndenumerate(mask):
    ans[v].append(data[k])

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

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