在列上过滤numpy矩阵 [英] filtering numpy matrix on a column
问题描述
我有一个如下的numpy矩阵:
I have a numpy matrix as follows:
data = np.matrix(
"5 3 1;"
"4 4 1;"
"6 4 1;"
"8 2 1;"
"3 5 1;"
"1 7 1;"
"5 4 1;"
"0 1 0;"
"2 0 0")
# Output:
matrix([[5, 3, 1],
[4, 4, 1],
[6, 4, 1],
[8, 2, 1],
[3, 5, 1],
[1, 7, 1],
[5, 4, 1],
[0, 1, 0],
[2, 0, 0]])
我想要的是在值为1的第三列上过滤矩阵;也就是说,我不想获取第三个值为0的行.总之,我想提取下面的矩阵:
what I want is to filter the matrix on the third column whose value is 1; that is, I do not want to get the rows whose 3rd value is 0. In short, I want to extract the matrix below:
matrix([[5, 3, 1],
[4, 4, 1],
[6, 4, 1],
[8, 2, 1],
[3, 5, 1],
[1, 7, 1],
[5, 4, 1]])
我尝试了几种组合来过滤它;但他们都没有为我工作.例如,以下代码将零行排除在外,但仅返回第一列.
I tried a few combinations to filter it; but none of them worked for me. For instance, the following code rules out the rows with zero, but it returns only the first column.
data[data[:,2]>0]
#Output:
matrix([[5, 4, 6, 8, 3, 1, 5]])
是否可以在不显式编写循环语句的情况下过滤此矩阵?
Is there a way to filter this matrix without explicitly writing loop statements?
推荐答案
使用np.array
代替np.matrix
,您可以进行简单的掩码索引编制,例如:
Using np.array
instead of np.matrix
allows you to do a simple mask indexing like:
a = a[a[:, 2] != 0]
要将np.matrix
转换为np.array
,您可以执行以下操作:
to convert from np.matrix
to np.array
you can do:
a = np.asarray(a)
这篇关于在列上过滤numpy矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!