[Python] Numpy, how to add column names to Numpy array

Discussão em 'Python' iniciado por Stack, Abril 21, 2025.

  1. Stack

    Stack Membro Participativo

    this probably has some duplicate threads but I honestly couldn't find a suitable solution. Pandas will be an easy solution but in the project I am working on will not include pandas as a dependency.

    I am trying to add column names to a Numpy array, basically turning it into structured array even though the data type are all the same.

    I tried:

    signal = np.array([[1,2,3],[1,2,3],[1,2,3]])
    col_names = ('left','right','center')
    signal = np.array(signal, dtype = [(n, 'int16') for n in col_names])


    but this returns:

    array([[(1, 1, 1), (2, 2, 2), (3, 3, 3)],
    [(1, 1, 1), (2, 2, 2), (3, 3, 3)],
    [(1, 1, 1), (2, 2, 2), (3, 3, 3)]],
    dtype=[('left', '<i2'), ('right', '<i2'), ('center', '<i2')])


    Basically, I have a Numpy array representing a multi-channel signal. I want to be able to subset the channels using column names:

    signal['left'] == signal[:,0] # True
    signal[['left','center']] == signal[:,[0,2]] # True


    I also saw a post someone advised against using structured array. Is there a potential downside to it? Say it makes the array slower to access?

    Continue reading...

Compartilhe esta Página