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

Generating a new array based on certain criterion in Python

I have an array X and a list T2. I want to create a new array Xnew such that elements of X are placed according to locations specified in T2. I present the current and expected outputs.

import numpy as np

X=np.array([4.15887486e+02, 3.52446375e+02, 2.81627790e+02, 1.33584716e+02,
       6.32045703e+01, 2.07514659e+02, 1.00000000e-24])

T2=[0, 3, 5, 8, 9, 10, 11]


def make_array(indices, values):
    rtrn = np.zeros(np.max(indices) + 1, dtype=values.dtype)
    rtrn[indices] = values
    return 

Xnew = np.array([make_array(Ti, Xi) for Ti, Xi in zip([T2], X)], dtype=object)
print("New X =",[Xnew])

The current output is

New X = [array([None], dtype=object)]

The expected 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

[array([[4.15887486e+02, 0.0, 0.0, 3.52446375e+02, 0.0,
        2.81627790e+02, 0.0, 0.0, 1.33584716e+02,
        6.32045703e+01, 2.07514659e+02, 1.00000000e-24]],
      dtype=object)]

>Solution :

You basically have what you need, but you are calling your function in a very weird way.

The function works with numpy arrays / lists as input, you don’t need to put in individual elements.

X = np.arange(5)
ind = np.asarray([1, 4, 3, 2, 10])

def make_array(indices, values):
    rtrn = np.zeros(np.max(indices) + 1, dtype=values.dtype)
    rtrn[indices] = values
    return rtrn

make_array(ind, X)  # array([0, 0, 3, 2, 1, 0, 0, 0, 0, 0, 4])
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