[Python] How to convert a Numpy 2D array with object dtype to a regular 2D array of floats

Discussão em 'Python' iniciado por Stack, Fevereiro 17, 2025.

  1. Stack

    Stack Membro Participativo

    As part of broader program I am working on, I ended up with object arrays with strings, 3D coordinates and etc all mixed. I know object arrays might not be very favorite in comparison to structured arrays but I am hoping to get around this without changing a lot of codes.

    Lets assume every row of my array obj_array (with N rows) has format of

    Single entry/object of obj_array: ['NAME',[10.0,20.0,30.0],....]


    Now, I am trying to load this object array and slice the 3D coordinate chunk. Up to here, everything works fine with simply asking lets say for .

    obj_array[:,[1,2,3]]


    However the result is also an object array and I will face problem as I want to form a 2D array of floats with:

    size [N,3] of N rows and 3 entries of X,Y,Z coordinates


    For now, I am looping over rows and assigning every row to a row of a destination 2D flot array to get around the problem. I am wondering if there is any better way with array conversion tools of numpy ? I tried a few things and could not get around it.

    Centers = np.zeros([N,3])

    for row in range(obj_array.shape[0]):
    Centers[row,:] = obj_array[row,1]


    Thanks

    Continue reading...

Compartilhe esta Página