[英]Match the elements of a vector and a matrix, returning a new matrix
I have the following numpy arrays:我有以下 numpy arrays:
[
[96.6074, 73.3443, 37.2574],
[11.2753, 39.8242, 42.1898],
[46.5815, 76.2492, 71.7398],
[4.99222, 7.64707, 6.5171],
]
[
True,
False,
False,
True
]
Now I want the elements of the boolean array to correspond to the rows of the float array.现在我希望 boolean 数组的元素对应于浮点数组的行。 I want to "match" them and create 2 new arrays, where:
我想“匹配”它们并创建 2 个新的 arrays,其中:
arr1
will contain only the rows of floatArray where the same rows (by index) in boolArray had True
arr1
将仅包含 floatArray 的行,其中 boolArray 中的相同行(按索引)具有True
arr2
will contain only the rows of floatArray where the same rows (by index) in boolArray had False
arr2
将仅包含 floatArray 的行,其中 boolArray 中的相同行(按索引)具有False
I'm think it can be done with a loop like this:我认为可以通过这样的循环来完成:
arr1 = np.array([])
arr2 = np.array([])
for idx, element in np.ndenumerate(boolArray):
if (element == True):
# append floatArray[idx] to arr1
else:
# append floatArray[idx] to arr2
But I'm new to python and I'm not really sure how to do it.. Any ideas?但我是 python 的新手,我不确定该怎么做。有什么想法吗?
You can simply use array masking:您可以简单地使用数组掩码:
>>> arr = np.array([
[96.6074, 73.3443, 37.2574],
[11.2753, 39.8242, 42.1898],
[46.5815, 76.2492, 71.7398],
[4.99222, 7.64707, 6.5171],
])
>>> mask = np.array([True, False, False, True])
>>> arr[mask]
array([[96.6074 , 73.3443 , 37.2574 ],
[ 4.99222, 7.64707, 6.5171 ]])
>>> arr[~mask]
array([[11.2753, 39.8242, 42.1898],
[46.5815, 76.2492, 71.7398]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.