简体   繁体   English

将蒙版应用于多维数组

[英]Applying a mask to an multidimensional array

I want to do this in a proper way: 我想以适当的方式做到这一点:

data = np.array(data)
data =[
[1, 1, 2, 1],
[0, 1, 3, 2],
[0, 2, 3, 2],
[2, 4, 3, 1],
[0, 2, 1, 4],
[3, 1, 4, 1]]

this should become (delete the lines that start with 0): 这应该成为(删除以0开头的行):

[1, 1, 2, 1]
[2, 4, 3, 1]
[3, 1, 4, 1]

So far I did it like this: 到目前为止,我这样做了:

lines = []
for i in range(0, len(data[0])):
    if data[0,i] != 0:
        lines.append(data[:,i])
lines = np.array(lines)

Then I found this fine method: 然后我发现了这个很好的方法:

mask = 1 <= data[0,:]

and now I want to apply that mask to that array. 现在我想将该掩码应用于该数组。 This Mask reads: [True, False, False, True, False, True] . 这个面具读取: [True, False, False, True, False, True] How do I do that? 我怎么做?

Why not just: 为什么不呢:

[ar for ar in data if ar[0] != 0]

This assumes that arrays are not empty. 这假设数组不为空。

I presume you have a numpy array based on the data[0,:] and data[0,i] you have in your question and you mean data[:, 0] : 我假设你有一个基于data[0,:]data[0,i]的numpy数组你的问题,你的意思是data[:, 0]

import numpy as np

data = np.array([
    [1, 1, 2, 1],
    [0, 1, 3, 2],
    [0, 2, 3, 2],
    [2, 4, 3, 1],
    [0, 2, 1, 4],
    [3, 1, 4, 1]])

data = data[data[:,0] != 0]
print(data)

Output: 输出:

[[1 1 2 1]
 [2 4 3 1]
 [3 1 4 1]]

data[0,:] is the first row [1 1 2 1] not the first column data[0,:]是第一行[1 1 2 1]而不是第一列

Using List comprehension 使用列表理解

In [56]: [elem for elem in data if elem[0] !=0]
Out[56]: [[1, 1, 2, 1], [2, 4, 3, 1], [3, 1, 4, 1]]

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

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