[Python] Pretty-print indices/coordinates of 2D Numpy array

Discussão em 'Python' iniciado por Stack, Agosto 6, 2025.

  1. Stack

    Stack Membro Participativo

    Does Numpy provide built-in capabilities to print the indices/coordinates of a 2-d Numpy array at its borders?

    What I mean is the following: Given, for example, the array

    a = np.arange(6).reshape(2, 3).astype(float)


    I would like to have a printout as follows:

    0 1 2
    0 0.0 1.0 2.0
    1 3.0 4.0 5.0


    It needn't be exactly like that, but the corresponding information should be conveyed. That is, I want to have a "header column" that shows the row indices (here: 0, 1) and a "header row" that shows the column indices (here: 0, 1, 2).

    At present, I simply use Pandas for this purpose (i.e. I convert the Numpy array to a Pandas DataFrame and then print the DataFrame). This is also suggested, for example, in this answer to a related question. However, this would always require Pandas, even if I don't use it for anything else in a given project.

    So my question, again, is: can I achieve the same printout only with Numpy (thus without Pandas)? Or, if not, is there a lightweight solution (in the sense of a few lines of code without an additional library) to achieve a similar output?

    Continue reading...

Compartilhe esta Página