简体   繁体   English

Numpy 按行掩码

[英]Numpy mask by rows

I have 2D array:我有二维数组:

matrix =np.array([[95,90,-1,55],[100,90,-1,80],[0,90,85,100]])

I try to choose 2 random rows, and ignore -1.我尝试选择 2 个随机行,并忽略 -1。

I tried:我试过了:

random_ints = np.random.choice(len(matrix), size=2, replace=False)
students = matrix[random_ints, :]
ignored = students[students != -1]

but the ignored var reshaped to 1D array for example:但被忽略的 var 重塑为一维数组,例如:

[95,90,55,100,90,80]

I want the ignored saved 2D for example:我想要忽略保存的 2D 例如:

[[95,90,55],[100,90,80]]

How can do that?怎么能这样做?

If you had equal number of elements to be left ( != -1 ) in each row, you could run:如果您在每一行中留下相同数量的元素( != -1 ),您可以运行:

np.apply_along_axis(lambda row: row[row != -1], 1, students)

To check this variant, set random_ints = np.array([0,1]) , select just the above rows to students and run the above code.要检查此变体,请将random_ints = np.array([0,1]) 、 select 设置为学生的上述行并运行上述代码。

But if the number of these element is different , Numpy will raise exception:但如果这些元素的数量不同Numpy将引发异常:

ValueError: could not broadcast input array from shape (3) into shape (4)

The reason is that (in this case) some rows have 4 elements to be left, whereas other - only 3 .原因是(在这种情况下)某些行有4 个元素要留下,而其他 - 只有3 个

Unfortunately, Numpy does not support "jagged" arrays (with different number of elements in each row).不幸的是, Numpy不支持“锯齿状”arrays(每行中的元素数量不同)。

You can get something like you wanted, but as a nested list (not a Numpy array):你可以得到你想要的东西,但是作为一个嵌套列表(不是Numpy数组):

result = []
for row in students:
    result.append(row[row != -1].tolist())

The result (for rows 2 and 1 ) is:结果(对于第 2行和第 1行)是:

[[0, 90, 85, 100], [100, 90, 80]]

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

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