[英]How to create an integer numpy 2darray of indexes from ndarray where elements are integers?
I'm trying to create an 2d numpy array in shape nxk where n is the dimension of the ndarray given and k is the amount of elements from the ndarray that are integers.我正在尝试创建一个形状为 nxk 的二维 numpy 数组,其中 n 是给定 ndarray 的维度,k 是 ndarray 中整数的元素数量。 Each row in the returned array should contain the indexes at which the condition holds at the relevant dimension.
返回数组中的每一行都应包含条件在相关维度处成立的索引。 For example, the ndarray is:
例如,ndarray 是:
array([[ 0. , -0.36650892, -0.51839849, 4.55566517, 4. ],
[ 5.21031078, 6.29935488, 8.29787346, 7.03293348, 8.74619707],
[ 9.36992033, 11. , 11.88485714, 12.98729128, 13.98447014],
[14. , 16.71828376, 16.15909201, 17.86503506, 19.12607872]])
Again, the condition is if the element is an integer so the returned array should be:同样,条件是元素是否为整数,因此返回的数组应为:
array([[0,0,2,3],
[0,4,1,0]])
Note that for the 0th row we want the 0th and 4th elements so we get [0,0,....],[0,4,...]
and so on.请注意,对于第 0 行,我们需要第 0 和第 4 个元素,因此我们得到
[0,0,....],[0,4,...]
等等。 I thought about creating a new array at the same shape as arr
with True at the integer element positions and False elsewhere.我考虑过创建一个与
arr
形状相同的新数组,其中整数元素位置为 True,其他位置为 False。 Not sure where to proceed with this though.不知道在哪里进行此操作。
Assuming a
the input array, you can compare to the rounded values to identify the integers, use numpy.where
to get their indices and np.vstack
to form the final array:假设
a
数组,您可以与舍入值进行比较以识别整数,使用numpy.where
获取它们的索引并使用np.vstack
形成最终数组:
np.vstack(np.where(a==a.round()))
output:输出:
array([[0, 0, 2, 3],
[0, 4, 1, 0]])
You can do something like this:你可以这样做:
import numpy as np
a = np.array([[ 0. , -0.36650892, -0.51839849, 4.55566517, 4. ],
[ 5.21031078, 6.29935488, 8.29787346, 7.03293348, 8.74619707],
[ 9.36992033, 11. , 11.88485714, 12.98729128, 13.98447014],
[14. , 16.71828376, 16.15909201, 17.86503506, 19.12607872]])
# check where the integer of a value is equal the value
mask = np.int_(a) == a
# get indexes where the mask is true
where = np.where(mask)
# make the output into an array with the shape you wanted
output = np.stack([where[0], where[1]])
print(output)
Output:输出:
array([[0, 0, 2, 3],
[0, 4, 1, 0]], dtype=int64)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.