[Python] Convert a slice of a structured array to regular NumPy array in NumPy 1.14

Discussão em 'Python' iniciado por Stack, Janeiro 16, 2025.

  1. Stack

    Stack Membro Participativo

    Note 1: None of the answers given to this question work in my case.

    Note 2: The solution must work in NumPy 1.14.

    Assume I have the following structured array:

    arr = np.array([(105.0, 34.0, 145.0, 217.0)], dtype=[('a', 'f4'), ('b', 'f4'), ('c', 'f4'), ('d', 'f4')]).

    Now I'm slicing into the structured data type like so:

    arr2 = arr[['a', 'b']]

    And now I'm trying to convert that slice into a regular array:

    out = arr2[0].view((np.float32, 2))

    which results in

    ValueError: Changing the dtype of a 0d array is only supported if the itemsize is unchanged

    What I would like to get is just a regular array like so:

    [105.0, 34.0]

    Note that this example is simplified in order to be minimal. In my real use case I'm obviously not dealing with an array that holds one element.

    I know that this solution works:

    out = np.asarray(list(arr2[0]))

    but I thought there must be a more efficient solution than copying data that is already in a NumPy array into a list and then back into an array. I assume there is a way to stay in NumPy an maybe not actually copy any data at all, I just don't know how.

    Continue reading...

Compartilhe esta Página