gpt4 book ai didi

python - 选择 numpy 数组中的行

转载 作者:太空宇宙 更新时间:2023-11-03 12:53:30 25 4
gpt4 key购买 nike

我有一个形状为 (n,4) 的 numpy 数组 (mat)。该数组有四列和大量 (n) 行。前三列代表我计算中的 xyz 列。我希望选择 numpy 数组中 x 列的值低于给定数字 (min_x) 或值高于给定数字 (max_x),并且 y 列的值低于给定数字 (min_y) 或高于给定数字 (max_y) 的值,并且其中z 列的值低于给定数字 (min_z) 或高于给定数字 (max_z)。

这就是我目前尝试实现此所需功能的方式:

import numpy as np

mark = np.where( ( (mat[:,0]<=min_x) | \
(mat[:,0]>max_x) ) & \
( (mat[:,1]<=min_y) | \
(mat[:,1]>max_y) ) & \
( (mat[:,2]<=min_z) | \
(mat[:,2]>max_z) ) )

mat_new = mat[:,mark[0]]

我使用的技术是否正确,是实现所需功能的最佳方式吗?我将不胜感激任何帮助。谢谢。

最佳答案

您现在拥有的看起来不错。但是由于您询问的是实现所需功能的其他方法:您可以为每个行索引创建一个 TrueFalse 的一维 bool 掩码。这是一个例子。

>>> import numpy as np
>>> np.random.seed(444)

>>> shape = 15, 4
>>> mat = np.random.randint(low=0, high=10, size=shape)
>>> mat
array([[3, 0, 7, 8],
[3, 4, 7, 6],
[8, 9, 2, 2],
[2, 0, 3, 8],
[0, 6, 6, 0],
[3, 0, 6, 7],
[9, 3, 8, 7],
[3, 2, 6, 9],
[2, 9, 8, 9],
[3, 2, 2, 8],
[1, 5, 6, 7],
[6, 0, 0, 0],
[0, 4, 8, 1],
[9, 8, 5, 8],
[9, 4, 6, 6]])

# The thresholds for x, y, z, respectively
>>> lower = np.array([5, 5, 4])
>>> upper = np.array([6, 6, 7])
>>> idx = len(lower)
# Parentheses are required here. NumPy boolean ops use | and &
# which have different operator precedence than `or` and `and`
>>> mask = np.all((mat[:, :idx] < lower) | (mat[:, :idx] > upper), axis=1)

>>> mask
array([False, False, True, True, False, False, True, False, True,
True, False, False, True, False, False])

现在通过 mask 索引 mat 会将其限制为 maskTrue 的行索引:

>>> mat[mask]
array([[8, 9, 2, 2],
[2, 0, 3, 8],
[9, 3, 8, 7],
[2, 9, 8, 9],
[3, 2, 2, 8],
[0, 4, 8, 1]])

这种方法有点不同的是它是可扩展的:不是单独指定每个坐标条件,而是可以在两个数组中指定它们,一个用于阈值上限,一个用于阈值下限,然后利用 NumPy 的矢量化和广播以构建掩码。

np.all() 表示,按行测试所有值是否为 True 它从中捕获“和”条件您的问题,而 | 运算符捕获“或”。

关于python - 选择 numpy 数组中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52341085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com