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

Flattening array based on conditions in Python

The present code flattens the array inv_r based on List. However, I want to define a condition when List is empty i.e. flatten inv_r without removing any element. Thus, the code should be able to handle empty as well non-empty List.

The current and desired outputs are attached.

import numpy as np

inv_r=(1e4)*np.array([[0.60800941, 0.79907128, 0.99442121],
       [0.61174008, 0.84891968, 0.71449188],
       [0.6211801 , 0.88869614, 0.91835812]])


List = []
Remove=np.ravel_multi_index(np.array(List).T, dims=inv_r.shape)
T1 = np.delete(inv_r.flatten(), Remove)
print([T1])

The current output is

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

ValueError: parameter multi_index must be a sequence of length 2

The desired output is

[array([7990.7128, 9944.2121, 6117.4008, 8489.1968, 7144.9188, 6211.801 ,
       8886.9614, 9183.5812])]

>Solution :

parameter multi_index must be a sequence of length 2, so np.ravel_multi_index will not work on the case of empty lists.
One easy way is to use if condition:

if len(List) != 0:
    Remove = np.ravel_multi_index(np.array(List).T, dims=inv_r.shape)
    T1 = np.delete(inv_r.flatten(), Remove)
else:
    T1 = inv_r.flatten()
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