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
๐ŸŒ
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')
Discussions

python - Programmatically add column names to numpy ndarray - Stack Overflow
But when I start calling columns by their field names, screwy things happen. The "column" is still an array with 108 columns... ... Any idea what's going wrong here? Adding headers should be a trivial operation, but I've been fighting this bug for hours. Help! ... Saullo G. P. Castro ยท 59.6k2828 gold badges194194 silver badges244244 bronze badges ... Save this answer. ... Show activity on this post. The problem is that you are thinking in terms of spreadsheet-like arrays, whereas NumPy ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Structured 2D Numpy Array: setting column and row names - Stack Overflow
I'm trying to find a nice way to take a 2d numpy array and attach column and row names as a structured array. For example: import numpy as np column_names = ['a', 'b', 'c'] row_names = ['1', '... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - numpy, named columns - Stack Overflow
Simple question about numpy: I load 100 values to a vector a. From this vector, I want to create an array A with 2 columns, where one column has name "C1" and second one "C2", one has type int32 and More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to add column names to Numpy array - Stack Overflow
I am trying to add column names to a Numpy array, basically turning it into structured array even though the data types are all the same. Pandas would be an easy solution, but the project I am work... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ add-rows-and-columns-headers-in-numpy-array.aspx
Add Rows and Columns Headers in NumPy Array
April 19, 2023 - # Import numpy import numpy as np # Import pandas import pandas as pd # Creating an array arr = np.random.randint(0, 10, size=36).reshape(6, 6) # Display original array print("Original array:\n", arr, "\n") # index and column names row_names = ["Row_1", "Row_2", "Row_3", "Row_4", "Row_5", "Row_6"] column_names = ["A", "B", "C", "D", "E", "F"] # Giving names to rows and columns res = pd.DataFrame(arr, index=row_names, columns=column_names) # Display result pd.set_option("max_columns", 6) print("Result:\n", res)
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ numpy-ndarray-get-column-names
Get the column names of a NumPy ndarray in Python | bobbyhadz
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( arr, np.dtype( [ ('Column_1', int), ('Column_2', int), ('Column_3', int) ] ) ) # ๐Ÿ‘‡๏ธ [(1, 2, 3) (4, 5, 6)] print(new_arr) # ๐Ÿ‘‡๏ธ ('Column_1', 'Column_2', 'Column_3') print(new_arr.dtype.names) print(new_arr['Column_1']) # ๐Ÿ‘‰๏ธ [1 4] The code for this article is available on GitHub ยท We defined a plain NumPy array and used the unstructured_to_structured() method to convert the unstructured array to a structured array. We set the array's column names and used dtype.names to get a tuple containing the names.
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ named-array
named-array ยท PyPI
January 6, 2022 - import numpy as np from named_array import named_array # the keyword arguments for named_array are exactly the same with numpy array, # but with an extra keyword `colnames`, which is a list of the column names for each column A = named_array([[1,2,3],[4,5,6]], colnames=['a', 'b', 'c']) >>> A named_array([[1, 2, 3], [4, 5, 6]]) # you can index a column by name >>> A['a'] named_array([1, 4]) # you can extract several columns as a new array # by a tuple or a list of column names >>> A['a', 'b'] array([[1, 2], [4, 5]]) >>> A[['a', 'b']] array([[1, 2], [4, 5]]) # set the column names of the named_a
      ยป pip install named-array
    
Published: Jan 07, 2022
Version: 0.11
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])
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ pandas_numpy โ€บ pandas_numpy-exercise-2.php
Create Pandas DataFrame from NumPy array with custom columns
December 21, 2024 - Creating a NumPy Array: numpy_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) Creates a 2D NumPy array named "numpy_array". Defining Custom Column Names: column_names = ['Column1', 'Column2', 'Column3'] Defines custom column names in a list ...
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ create-a-pandas-dataframe-from-a-numpy-array-and-specify-the-index-column-and-column-headers
Create a Pandas DataFrame from a Numpy array and specify the index column and column headers - GeeksforGeeks
August 21, 2020 - This method can be used if the index column and column header names follow some pattern. ... # Python program to Create a # Pandas DataFrame from a Numpy # array and specify the index column # and column headers # import required libraries import pandas as pd import numpy as np # creating a numpy array numpyArray = np.array([[15, 22, 43], [33, 24, 56]]) # defining index for the # Pandas dataframe index = ['Row_' + str(i) for i in range(1, len(numpyArray) + 1)] # defining column headers for the # Pandas dataframe columns = ['Column_' + str(i) for i in range(1, len(numpyArray[0]) + 1)] # generating the Pandas dataframe # from the Numpy array and specifying # details of index and column headers panda_df = pd.DataFrame(numpyArray , index = index, columns = columns) # printing the dataframe print(panda_df)
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)
๐ŸŒ
Readthedocs
scipy-cookbook.readthedocs.io โ€บ items โ€บ Recarray.html
Addressing Array Columns by Name โ€” SciPy Cookbook documentation
There are two very closely related ways to access array columns by name: recarrays and structured arrays. Structured arrays are just ndarrays with a complicated data type: ... #!python numbers=disable In [1]: from numpy import * In [2]: ones(3, dtype=dtype([('foo', int), ('bar', float)])) Out[2]: array([(1, 1.0), (1, 1.0), (1, 1.0)], dtype=[('foo', '<i4'), ('bar', '<f8')]) In [3]: r = _ In [4]: r['foo'] Out[4]: array([1, 1, 1])
๐ŸŒ
GitHub
github.com โ€บ astropy โ€บ astropy โ€บ issues โ€บ 7320
initialize Table with numpy array and column names ยท Issue #7320 ยท astropy/astropy
March 21, 2018 - astropy v3.0.1; numpy v1.14.2 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-47-5d2d540b4498> in <module>() 3 names = ['col{0}'.format(i) for i in range(len(data))] ----> 4 Table(data, names=names) ~/anaconda3/lib/python3.6/site-packages/astropy/table/table.py in __init__(self, data, masked, names, dtype, meta, copy, rows, copy_indices, **kwargs) 403 names = [fix_column_name(name) for name in names] 404 --> 405 self._check_names_dtype(names, dtype, n_cols) 406 407 # Finally do the real initialization ~/ana
Author: astropy
๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ get-the-column-names-of-a-numpy-ndarray.aspx
Python - Get the column names of a NumPy ndarray
For this purpose, we will use dtype.names() with the created array and this will return an array of all the names of the columns. ... # Import numpy import numpy as np # Creating a numpy array arr = np.genfromtxt("data.txt",names=True) # Display original array print("Original array:\n",arr,"\n") ...
๐ŸŒ
NumPy
numpy.org โ€บ devdocs โ€บ reference โ€บ generated โ€บ numpy.recarray.html
numpy.recarray โ€” NumPy v2.5.dev0 Manual
The name of each column, e.g. ('x', 'y', 'z'). ... By default, a new array is created of the given shape and data-type. If buf is specified and is an object exposing the buffer interface, the array will use the memory from the existing buffer.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ create-a-dataframe-from-a-numpy-array-and-specify-the-index-column-and-column-headers
Create a DataFrame from a Numpy array and specify the index column and column headers - GeeksforGeeks
July 28, 2020 - # importiong the modules import pandas as pd import numpy as np # creating the Numpy array array = np.array([['Aditya', 20], ['Samruddhi', 15], ['Rohan', 21], ['Anantha', 20], ['Abhinandan', 21]]) # creating a list of index names index_values = ['A', 'B', 'C', 'D', 'E'] # creating a list of column names column_values = ['Names', 'Age'] # creating the dataframe df = pd.DataFrame(data = array, index = index_values, columns = column_values) # displaying the dataframe print(df) Output : Example 3 :