Home > Blockchain >  Generating a new array based on certain criterion in Python
Generating a new array based on certain criterion in Python

Time:01-13

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

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

CodePudding user response:

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