获取索引并创建基于 Python 的 numpy 数组
Obtaining indexes and creating an Python-based numpy array
我在将 Matlab 转换为 Python 代码时遇到问题,特别是涉及矩阵/数组时。
在这里,我有一个名为 output
的二维 numpy
数组,我正在计算高于变量 [=] 的元素的行主索引 t_ind
的向量16=]:
t_ind = np.flatnonzero(output > vmax)
现在我想使用这些索引创建一个基于此的矩阵。在 MATLAB 中,我可以直接这样做:
output(t_ind) = 2*vmax - output(t_ind);
但在 Python 这行不通。具体来说,我收到 IndexError
说明我越界了。
我试图弄清楚,但我能想到的最优雅的解决方案是使用 np.hstack()
将数组转换为向量,比较索引,将它们收集到另一个变量中,然后返回。
你能解释一下吗?
对于一维数组,np.flatnonzero
的使用是正确的。具体来说,等效的 numpy
语法为:
output[t_ind] = 2*vmax - output[t_ind]
此外,您可以使用布尔运算符实现相同的目的。 MATLAB 也支持此功能,因此如果您想在两者之间进行转换,布尔值(或 MATLAB 领域中的 logical
)是更好的方法:
output[output > vmax] = 2*vmax - output[output > vmax]
对于 2D 情况,您不使用 np.flatnonzero
。使用 np.where
代替:
t_ind = np.where(output > v_max)
output[t_ind] = 2*vmax - output[t_ind]
t_ind
将 return 一个 numpy
数组的元组,其中第一个元素为您提供行位置,第二个元素为您提供满足布尔值的那些值的列位置置于 np.where
.
中的条件
请注意,布尔索引的情况仍然适用于您想要的矩阵的任何维度。但是,np.flatnonzero
将计算满足 np.flatnonzero
输入条件的那些点的 行优先 索引。出现错误的原因是因为您试图使用行优先索引来访问二维数组。尽管 Python 支持线性索引,但 numpy
不支持 - 您必须独立访问每个维度才能进行此索引,这就是将 t_ind
指定为输入索引的原因output
会做。
Numpy 同时支持布尔索引和多维索引,因此您无需跳过所有这些步骤,这里有两种方法可以满足您的需求:
# The setup
import numpy as np
a = np.random.random((3, 4))
vmax = 1.2
output = np.zeros(a.shape, a.dtype)
# Method one, use a boolean array to index
mask = a > .5
output[mask] = 2 * vmax - a[mask]
# Method tow, use indices to index.
t_ind = np.nonzero(a > .5)
output[t_ind] = 2 * vmax - a[t_ind]
我在将 Matlab 转换为 Python 代码时遇到问题,特别是涉及矩阵/数组时。
在这里,我有一个名为 output
的二维 numpy
数组,我正在计算高于变量 [=] 的元素的行主索引 t_ind
的向量16=]:
t_ind = np.flatnonzero(output > vmax)
现在我想使用这些索引创建一个基于此的矩阵。在 MATLAB 中,我可以直接这样做:
output(t_ind) = 2*vmax - output(t_ind);
但在 Python 这行不通。具体来说,我收到 IndexError
说明我越界了。
我试图弄清楚,但我能想到的最优雅的解决方案是使用 np.hstack()
将数组转换为向量,比较索引,将它们收集到另一个变量中,然后返回。
你能解释一下吗?
对于一维数组,np.flatnonzero
的使用是正确的。具体来说,等效的 numpy
语法为:
output[t_ind] = 2*vmax - output[t_ind]
此外,您可以使用布尔运算符实现相同的目的。 MATLAB 也支持此功能,因此如果您想在两者之间进行转换,布尔值(或 MATLAB 领域中的 logical
)是更好的方法:
output[output > vmax] = 2*vmax - output[output > vmax]
对于 2D 情况,您不使用 np.flatnonzero
。使用 np.where
代替:
t_ind = np.where(output > v_max)
output[t_ind] = 2*vmax - output[t_ind]
t_ind
将 return 一个 numpy
数组的元组,其中第一个元素为您提供行位置,第二个元素为您提供满足布尔值的那些值的列位置置于 np.where
.
请注意,布尔索引的情况仍然适用于您想要的矩阵的任何维度。但是,np.flatnonzero
将计算满足 np.flatnonzero
输入条件的那些点的 行优先 索引。出现错误的原因是因为您试图使用行优先索引来访问二维数组。尽管 Python 支持线性索引,但 numpy
不支持 - 您必须独立访问每个维度才能进行此索引,这就是将 t_ind
指定为输入索引的原因output
会做。
Numpy 同时支持布尔索引和多维索引,因此您无需跳过所有这些步骤,这里有两种方法可以满足您的需求:
# The setup
import numpy as np
a = np.random.random((3, 4))
vmax = 1.2
output = np.zeros(a.shape, a.dtype)
# Method one, use a boolean array to index
mask = a > .5
output[mask] = 2 * vmax - a[mask]
# Method tow, use indices to index.
t_ind = np.nonzero(a > .5)
output[t_ind] = 2 * vmax - a[t_ind]