Home > Back-end >  Flattening array based on conditions in Python
Flattening array based on conditions in Python

Time:06-15

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

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])]

CodePudding user response:

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()
  • Related