Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 n x k where n is the dimension of the ndarray given and k is the amount of elements from the ndarray that are integers. Each row in the returned array should contain the indexes at which the condition holds at the relevant dimension.
For example, the ndarray is:

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.
I thought about creating a new array at the same shape as arr with True at the integer element positions and False elsewhere. Not sure where to proceed with this though.
Any help would be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:

np.vstack(np.where(a==a.round()))

output:

array([[0, 0, 2, 3],
       [0, 4, 1, 0]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading