按条件提取numpy数组中的特定列

问题描述 投票:-1回答:1

我有一个家庭作业,通过条件(而不是范围)选择特定列,从另一个二维np数组中提取二维numpy数组。

所以我有一个形状A与形状(3, 50000)。我试图得到一个形状为(3, x)的新数组,用于某些x < 50000 with the original columns ofAthat satisfy the third cell in the column is-0.4 <z <0.1`。

例如,如果:

A = [[1,2,3],[2,0.5,0],[9,-2,-0.2],[0,0,0.5]]

我希望回来:

B = [[2,0.5,0],[9,-2,-0.2]

我试图在我想要的列上创建一个bool 1 rank数组,以及一些如何在两者之间组合。它的输出问题是1级数组,这不是我要找的。我得到了一些ValueErrors ..

bool_idx = (-0.4 < x_y_z[2] < 0.1)

这段代码有些麻烦:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我可以用一些循环来做,但NumPy有这么多美丽的功能我相信我在这里遗漏了一些东西..

python python-3.x numpy numpy-ndarray
1个回答
2
投票

在Python中,表达式-0.4 < x_y_z[2] < 0.1大致相当于-0.4 < x_y_z[2] and x_y_z[2] < 0.1and运算符通过将表达式转换为bool来确定表达式的每个部分的真值。与Python列表和元组不同,numpy数组不支持转换。

指定条件的正确方法是使用按位&(明确且非短路),而不是隐式and(在这种情况下短路且不明确):

condition = ((x_y_z[2, :] > - 0.4) & (x_y_z[2, :] < 0.1))

condition是一个布尔掩码,用于选择所需的列。您可以使用简单切片选择行:

selection = x_y_z[:, condition] 
© www.soinside.com 2019 - 2024. All rights reserved.