在Python/Numpy中选择满足条件的特定行,且只选择某些列

27 投票
5 回答
93843 浏览
提问于 2025-04-18 07:49

我有一个包含4列的numpy数组,我想选择第1、3和4列,前提是第2列的值满足某个条件(比如说是一个固定的值)。我先尝试只选择行,但还是保留了所有4列,代码如下:

I = A[A[:,1] == i]

这个方法是有效的。然后我又尝试了一种方法,类似于我非常熟悉的MATLAB:

I = A[A[:,1] == i, [0,2,3]]

但是这个方法不行。那我该怎么做呢?


示例数据:

 >>> A = np.array([[1,2,3,4],[6,1,3,4],[3,2,5,6]])
 >>> print A
 [[1 2 3 4]
  [6 1 3 4]
  [3 2 5 6]]
 >>> i = 2
     
 # I want to get the columns 1, 3 and 4 
 # for every row which has the value i in the second column. 
 # In this case, this would be row 1 and 3 with columns 1, 3 and 4:
 [[1 3 4]
  [3 5 6]]
 

现在我正在使用这个方法:

I = A[A[:,1] == i]
I = I[:, [0,2,3]]

但我觉得应该有更好的方法来实现这个...(我习惯使用MATLAB)

5 个回答

1

我希望这能回答你的问题,这里有一段我用pandas写的脚本:

df_targetrows = df.loc[df[col2filter]*somecondition*, [col1,col2,...,coln]]

比如说,

targets = stockdf.loc[stockdf['rtns'] > .04, ['symbol','date','rtns']]

这段代码会从stockdf中返回一个只包含['symbol','date','rtns']这几列的数据框,并且只有当rtns这一列的值大于0.04时,才会显示那一行的数据。

希望这对你有帮助。

1

这个方法也可以用。

I = np.array([row[[x for x in range(A.shape[1]) if x != i-1]] for row in A if row[i-1] == i])
print I

补充说明:因为索引是从0开始的,所以

i-1

应该使用这个。

3

这段代码是用来做一些特定操作的,但具体的功能和效果需要根据上下文来理解。它可能涉及到一些编程语言的基础知识,比如变量、函数或者控制结构等。

如果你是编程新手,可以把这段代码想象成一个小工具,它可以帮助你完成某个任务。每一行代码就像是给这个工具下达的指令,告诉它该怎么做。

在学习这段代码的时候,可以尝试逐行分析,看看每一行的作用是什么,慢慢就能理解它的整体功能了。

>>> a=np.array([[1,2,3], [1,3,4], [2,2,5]])
>>> a[a[:,0]==1][:,[0,1]]
array([[1, 2],
       [1, 3]])
>>> 
6

如果你不想用布尔值(真或假)来表示位置,而是想用索引(位置的数字),你可以这样写:

A[:, [0, 2, 3]][A[:, 1] == i]

回到你的例子:

>>> A = np.array([[1,2,3,4],[6,1,3,4],[3,2,5,6]])
>>> print A
[[1 2 3 4]
 [6 1 3 4]
 [3 2 5 6]]
>>> i = 2
>>> print A[:, [0, 2, 3]][A[:, 1] == i]
[[1 3 4]
 [3 5 6]]

说真的,

38
>>> a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
>>> a
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

>>> a[a[:,0] > 3] # select rows where first column is greater than 3
array([[ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

>>> a[a[:,0] > 3][:,np.array([True, True, False, True])] # select columns
array([[ 5,  6,  8],
       [ 9, 10, 12]])

# fancier equivalent of the previous
>>> a[np.ix_(a[:,0] > 3, np.array([True, True, False, True]))]
array([[ 5,  6,  8],
       [ 9, 10, 12]])

关于那个不太常见的 np.ix_() 的解释,可以查看这个链接:https://stackoverflow.com/a/13599843/4323

最后,我们可以通过提供列号的列表来简化操作,而不是使用繁琐的布尔掩码:

>>> a[np.ix_(a[:,0] > 3, (0,1,3))]
array([[ 5,  6,  8],
       [ 9, 10, 12]])

撰写回答