First because your question asks about giving names to arrays, I feel obligated to point out that using "structured arrays" for the purpose of giving names is probably not the best approach. We often like to give names to rows/columns when we're working with tables, if this is the case I suggest you try something like pandas which is awesome. If you simply want to organize some data in your code, a dictionary of arrays is often much better than a structured array, so for example you can do:

Y = {'ID':X[0], 'Ring':X[1]}

With that out of the way, if you want to use a structured array, here is the clearest way to do it in my opinion:

import numpy as np

RING = [1,2,2,3,3,3]
ID = [1,2,3,4,5,6]
X = np.array([ID, RING])

dt = {'names':['ID', 'Ring'], 'formats':[int, int]}
Y = np.zeros(len(RING), dtype=dt)
Y['ID'] = X[0]
Y['Ring'] = X[1]
Answer from Bi Rico on Stack Overflow
🌐
IncludeHelp
includehelp.com › python › add-rows-and-columns-headers-in-numpy-array.aspx
Add Rows and Columns Headers in NumPy Array
April 19, 2023 - And, we have to add the column's ... where you can assign index and column names during DataFrame creation by using the pd.DataFrame(arr, index = "rows", columns = "cols")....
Top answer
1 of 4
1

The correct data input form for a structured array is a list of tuples:

In [71]: signal = [(1,2,3),(2,3,1),(3,2,1)] 
    ...: col_names = ('left','right','center') 
    ...: signal = np.array(signal, dtype = [(n, 'int16') for n in col_names])   
In [72]:                                                                        
In [72]: signal                                                                 
Out[72]: 
array([(1, 2, 3), (2, 3, 1), (3, 2, 1)],
      dtype=[('left', '<i2'), ('right', '<i2'), ('center', '<i2')])

1.16 has added a couple of functions that make it easier to convert to and from structured arrays:

In [73]: import numpy.lib.recfunctions as rfn                                   
In [74]: signal = np.array([[1,2,3],[1,2,3],[1,2,3]])                           
In [75]: dt = np.dtype([(n, 'int16') for n in col_names])                       
In [76]: dt                                                                     
Out[76]: dtype([('left', '<i2'), ('right', '<i2'), ('center', '<i2')])
In [77]: rfn.unstructured_to_structured(signal, dt)                             
Out[77]: 
array([(1, 2, 3), (1, 2, 3), (1, 2, 3)],
      dtype=[('left', '<i2'), ('right', '<i2'), ('center', '<i2')])

Applying this dt to signal has a problem:

In [82]: signal.view(dt)                                                        
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-82-f0fa01ce8128> in <module>
----> 1 signal.view(dt)

ValueError: When changing to a smaller dtype, its size must be a divisor of the size of original dtype

We can get around that by first converting signal to a compatible dtype:

In [83]: signal.astype('i2').view(dt)                                           
Out[83]: 
array([[(1, 2, 3)],
       [(1, 2, 3)],
       [(1, 2, 3)]],
      dtype=[('left', '<i2'), ('right', '<i2'), ('center', '<i2')])

But note that Out[83] shape is (3,1). The other arrays were shape (3,). view has always had this shape problem when converting to/from structured arrays. That's part of why the newer functions are easier to use.

2 of 4
1
values = [(1,2,3),(1,2,3),(1,2,3)]
signal = np.array(values, [('left', '<i2'), ('center', '<i2'), ('right', '<i2')])
signal['right']
array([3, 3, 3], dtype=int16)
Top answer
1 of 2
2

Maybe this can help (if you don't want to use numpy):

headers = ['foo', 'bar', 'baz', 'other']
l = len(headers)

arr = [["xxx" for i in range(l)] for j in range(l)]

# adding top row
arr = [headers] + arr

# adding first column
headers_mod = ['Title'] + headers
new_arr = [[headers_mod[i]]+arr[i] for i in range(l+1)]

for i in new_arr:
  print(*i)

gives you the output as:

Title foo bar baz other
foo xxx xxx xxx xxx
bar xxx xxx xxx xxx
baz xxx xxx xxx xxx
other xxx xxx xxx xxx

Otherwise, when dealing with array manipulations in python try going with numpy, pandas, as they provide better operations like by giving option for axis, transpose, etc.

2 of 2
1

numpy is excellent for tables, but for a labeled table like this pandas might be better for your needs.

Solution using numpy:

import numpy as np

# The header that i want to add
headers = ['foo', 'bar', 'baz', 'other']

ll = len(headers)+1
data = [['xxx' for _ in range(ll)] for j in range(ll)]

data = np.array(data, dtype=object)

data[0,0] = 'Title'
data[0,1:] = headers
data[1:,0] = headers

print(data)

prints

[['Title' 'foo' 'bar' 'baz' 'other']
 ['foo' 'xxx' 'xxx' 'xxx' 'xxx']
 ['bar' 'xxx' 'xxx' 'xxx' 'xxx']
 ['baz' 'xxx' 'xxx' 'xxx' 'xxx']
 ['other' 'xxx' 'xxx' 'xxx' 'xxx']]

Setting dtype to object allows your array to mix strings and other data types you might want to use. If your data is just strings then you can use 'UN' as the dtype, where N is the longest string you plan to use. (Numpy, when making an all string array automatically picks your longest string as the maximum length for the strings, which is fine unless your strings are all shorter than the headers you plan to add.)

Alternate version of the above code:

import numpy as np

# The header that i want to add
headers = ['foo', 'bar', 'baz', 'other']

# Add Title to headers  to simply later assignment
headers = ['Title'] + headers

ll = len(headers)
data = [['xxx' for _ in range(ll)] for j in range(ll)]

data = np.array(data)

data[0,:] = headers
data[:,0] = headers

print(data)

pandas, on the other hand, is explicitly designed to handle headers

import numpy as np, pandas as pd

# The header that i want to add
headers = ['foo', 'bar', 'baz', 'other']

ll = len(headers) + 1
data = [['xxx' for _ in range(ll)] for j in range(ll)]

data = np.array(data)

data = pd.DataFrame(data[1:,1:], columns=headers, index=headers)
data.columns.name = 'Title'

data.loc['foo','bar'] = 'yes'
print(data)
print('')
print(data['bar'])
print('')
print(data.loc['foo',:])

prints

Title  foo  bar  baz other
foo    xxx  yes  xxx   xxx
bar    xxx  xxx  xxx   xxx
baz    xxx  xxx  xxx   xxx
other  xxx  xxx  xxx   xxx

foo      yes
bar      xxx
baz      xxx
other    xxx
Name: bar, dtype: object

Title
foo      xxx
bar      yes
baz      xxx
other    xxx
Name: foo, dtype: object
Top answer
1 of 2
15

The problem is that you are thinking in terms of spreadsheet-like arrays, whereas NumPy does use different concepts.

Here is what you must know about NumPy:

  1. NumPy arrays only contain elements of a single type.
  2. If you need spreadsheet-like "columns", this type must be some tuple-like type. Such arrays are called Structured Arrays, because their elements are structures (i.e. tuples).

In your case, NumPy would thus take your 2-dimensional regular array and produce a one-dimensional array whose type is a 108-element tuple (the spreadsheet array that you are thinking of is 2-dimensional).

These choices were probably made for efficiency reasons: all the elements of an array have the same type and therefore have the same size: they can be accessed, at a low-level, very simply and quickly.

Now, as user545424 showed, there is a simple NumPy answer to what you want to do (genfromtxt() accepts a names argument with column names).

If you want to convert your array from a regular NumPy ndarray to a structured array, you can do:

data.view(dtype=[(n, 'float64') for n in csv_names]).reshape(len(data))

(you were close: you used astype() instead of view()).

You can also check the answers to quite a few Stackoverflow questions, including Converting a 2D numpy array to a structured array and how to convert regular numpy array to record array?.

2 of 2
3

Unfortunately, I don't know what is going on when you try to add the field names, but I do know that you can build the array you want directly from the file via

data = np.genfromtxt(csv_file, delimiter=',', names=True)

EDIT:

It seems like adding field names only works when the input is a list of tuples:

data = np.array(map(tuple,data), [(n, 'float64') for n in csv_names])
🌐
Medium
medium.com › @heyamit10 › numpy-add-column-guide-0427e394b333
NumPy Add Column Guide. I understand that learning data science… | by Hey Amit | Medium
March 6, 2025 - You might be thinking, “But why?” Well, NumPy expects the new column to match the number of rows in arr. Here, arr has 3 rows, but wrong_col has only 2 elements. That’s like trying to fit a square peg in a round hole—it just won’t work. ... # Correct column with 3 elements correct_col = np.array([16, 17, 18]) result = np.hstack((arr, correct_col.reshape(-1, 1))) print(result)
Find elsewhere
🌐
Bobby Hadz
bobbyhadz.com › blog › numpy-ndarray-get-column-names
Get the column names of a NumPy ndarray in Python | bobbyhadz
If you need to add column names to a plain NumPy ndarray, use the unstructured_to_structured method. ... Copied!import numpy as np import numpy.lib.recfunctions as rfn arr = np.array([[1, 2, 3], [4, 5, 6]]) new_arr = rfn.unstructured_to_structured( ...
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.dtype.names.html
numpy.dtype.names — NumPy v1.26 Manual
January 31, 2021 - >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> dt.names ('name', 'grades')
🌐
GeeksforGeeks
geeksforgeeks.org › python-ways-to-add-row-columns-in-numpy-array
Python | Ways to add row/columns in numpy array - GeeksforGeeks
March 22, 2023 - import numpy as np ini_array = np.array([[1, 2, 3], [45, 4, 7], [9, 6, 10]]) # Array to be added as column column_to_be_added = np.array([[1], [2], [3]]) # Adding column to array using append() method arr = np.concatenate([ini_array, ...
🌐
Blogger
vincentgriffins.blogspot.com › home › column › multiplying matrices › names › python
Python Numpy Array Add Column Names - Vincent Griffin's Multiplying Matrices
July 30, 2021 - Column For row. Now you can get columns in Numpy arrays. Fortunately you can easily do this using the following syntax. Python May 29 2021 You may use add_prefix in order to add a prefix to each column name in Pandas DataFrame. Lets return column second to sixth but every second column.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-ways-to-add-row-columns-in-numpy-array
Ways to Add Row/Columns in Numpy Array - Python - GeeksforGeeks
June 24, 2025 - Just make sure the new column has the same number of rows as the original array. np.append() adds values to a NumPy array along a specified axis or flattens if axis is not set.
🌐
Pdxdev
python.pdxdev.com › numpy › how-to-add-a-column-to-a-numpy-array
Adding Columns to NumPy Arrays
Now, you want to include their grades (A, B, C, etc.). Adding a “Grade” column allows you to store this new information alongside the existing data, making your analysis more comprehensive. ... This function stacks 1D arrays column-wise into a new 2D array. It’s ideal when you already have separate arrays representing the data for each column. import numpy as np # Existing data: names and exam scores names = np.array(['Alice', 'Bob', 'Charlie']) scores = np.array([85, 92, 78]) # New data: grades grades = np.array(['B', 'A', 'C']) # Combine the arrays into a new array with columns for names, scores, and grades combined_data = np.column_stack((names, scores, grades)) print(combined_data)
🌐
Python Help
pythonhelp.org › numpy › how-to-add-column-in-numpy-array
How to Add Column in NumPy Array
June 8, 2023 - Data Analysis: Adding new columns to an array allows for more comprehensive analysis, enabling better insights into the data. Here’s a step-by-step guide on how to add a column to a NumPy array using Python: