0

I am trying to add column names to an existing numpy array.

I have seen in this question that .dtype.names provides (and sets) the column names of a numpy array.

However when I have an existing array and I try to name the columns I get the following message.

I am sure it is a basic question and I am missing something pretty basic, but still can not find the answer:

a = np.array([[1,2,3],[4,5,6]])
a.dtype.names = 'ColA', 'ColB', 'ColC'

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-247-793bf2e18e51> in <module>
      1 a = np.array([[1,2,3],[4,5,6]])
----> 2 a.dtype.names = ('ColA', 'ColB', 'ColC')

ValueError: there are no fields defined

EDIT:

It appears that only structured arrays can have named columns in numpy (numpy, named columns) and that numpy arrays can not have named columns.

1
  • DSM's answer in the link shows how to create a structured array. You can't 'add' column names to a existing array. Commented Oct 24, 2020 at 10:41

1 Answer 1

2

You can convert your "plain" (unstructured) array to a structured array, where each column has its name and type.

First import:

import numpy.lib.recfunctions as rfn

Assume that your source array has been created as:

a = np.array([[1,2,3], [4,5,6]])

Then to convert it to a structured array, run:

b = rfn.unstructured_to_structured(a,
    np.dtype([('Col_1', int), ('Col_2', int), ('Col_3', int)]))

(column names and types are arbitrary). If you want, you can pass different types to each column, e.g. some columns can be of float type.

The result is:

array([(1, 2, 3), (4, 5, 6)],
      dtype=[('Col_1', '<i4'), ('Col_2', '<i4'), ('Col_3', '<i4')])

If you want to refer to a column by name, run b['Col_1'] getting array([1, 4]).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.