With pandas.DataFrame.to_csv you can write the columns and the index to a file:

import numpy as np
import pandas as pd

A = np.random.randint(0, 10, size=36).reshape(6, 6)
names = [_ for _ in 'abcdef']
df = pd.DataFrame(A, index=names, columns=names)
df.to_csv('df.csv', index=True, header=True, sep=' ')

will give you the following df.csv file:

  a b c d e f 
a 1 5 5 0 4 4 
b 2 7 5 4 0 9 
c 6 5 6 9 7 0 
d 4 3 7 9 9 3 
e 8 1 5 1 9 0 
f 2 8 0 0 5 1    
Answer from bmu on Stack Overflow
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
🌐
IncludeHelp
includehelp.com › python › add-rows-and-columns-headers-in-numpy-array.aspx
Add Rows and Columns Headers in NumPy Array
April 19, 2023 - To add rows/columns headers in the NumPy array, you need to convert this array into a DataFrame where you can assign index and column names during DataFrame creation by using the pd.DataFrame(arr, index = "rows", columns = "cols").
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-168.php
Python NumPy: Convert Pandas dataframe to Numpy array with headers - w3resource
August 29, 2025 - Create a function that extracts header names from a DataFrame and prepends them to the converted array. Implement a solution that ensures the resulting NumPy array preserves data types from the DataFrame.
🌐
CSDN
devpress.csdn.net › python › 6304618f7e6682346619acea.html
Adding Header to Numpy array - Python - DevPress官方社区
August 23, 2022 - import numpy a = numpy.array([[0.0,1.630000e+01,1.990000e+01,1.840000e+01], [1.0,1.630000e+01,1.990000e+01,1.840000e+01], [2.0,1.630000e+01,1.990000e+01,1.840000e+01]]) fmt = ",".join(["%s"] + [".6e"] * (a.shape[1]-1)) # numpy.savetxt, at least as of numpy 1.6.2, writes bytes # to file, which doesn't work with a file open in text mode. To # work around this deficiency, open the file in binary mode, and # write out the header as bytes.
🌐
GeeksforGeeks
geeksforgeeks.org › python › 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
July 15, 2025 - Here, the number of iterations is defined by the length of the sub-array inside the Numpy array. 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 # Pa
Find elsewhere
🌐
w3resource
w3resource.com › python-exercises › pandas › python-pandas-data-frame-exercise-44.php
Pandas: Create a DataFrame from a Numpy array and specify the index column and column headers - w3resource
September 5, 2025 - Write a Pandas program to form a DataFrame from a 2D NumPy array and then rename the index and column headers using a predefined list.
Top answer
1 of 2
4

1.) I would recommend storing column and row header information in a separate data structure. Numpy matrices can store mixed data types (in this case strings and floats), I try to avoid it. Mixing data types is messy and seems inefficient to me. If you want to, you can make your own class with your matrix data and header information in it. It seems like a cleaner solution to me.

2.) No, summaryMeansArray is set-up to have 11 rows and 6 columns. The first dimension of a matrix is the number of rows. You can get the transpose of summaryMeansArray with summaryMeansArray.T. When you are taking the mean of summary3dArray on the 0th axis, the next axis becomes the rows and the one after that the columns.

Edit: As per request, you can create a python list from a numpy array with the method tolist(). For instance,

newMeansArray = summaryMeansArray.tolist()

Then you can insert the column headers using

newMeansArray.insert(0,headers)

Inserting the row headers can be done with:

newMeansArray[i].insert(0,rowheader)

for each row i. Of course, if you've already inserted the column headers, then the counting for i starts with 1 rather than 0.

2 of 2
0

I agree with Justin Peel's answer, regarding question #1 (row/header labels).

I created my own class that allows me to decorate a matrix with extra data necessary to my task at hand (for example: row and column labels, a descriptive text for each row, or numerical properties of a row that are external to or independent of the matrix values).

My first solution that I used for almost 2 years was to have an object for each matrix row, where I would store each row's matrix values in a dictionary, with the dictionary key (ID) providing the second piece of information for that pair's matrix value. This was quite useful, especially for non-square matrices, and matrix manipulations and output were isolated cleanly.

However, I ran into a problem with this design: scalability. When using square, symmetric matrices, I needed 91 MB of memory for a 1000x1000 matrix, 327 MB of memory for a 2000x2000 matrix, and 1900 MB of memory for a 5000x5000 matrix. For my recent project that works on the order of 20000x20000 matrix entries, I will quickly and disastrously use up all of my workstation's 8GB of RAM and more.

My second solution was to have a single dictionary of (ID1,ID2)-->value mappings. Compared to my first solution, a 1000x1000 matrix required only 20 MB of memory. This solution also fails miserably in the scalability department, but in a different way, because the time to create and store C(1000+1,2)=500500 mappings was over 3 minutes, compared to 0.88 seconds when using my first design.

My third and current solution was to create a mapping between the numpy matrix row/column index and a matrix row/column label. Using numpy directly with a 5000x5000 matrix required 202 MB of memory on my system, a 10000x1000 matrix required 774 MB, and a 20000x2000 matrix required 3000 MB. A mapping of 20000 IDs to row/column indexes required 5 MB of memory on my system, which is negligible compared to the value matrix itself.

If one is processing only small matrices less than 100x100 elements, then my first solution will be quick and the implemented data structure will be easy to manipulate and extend. However, if you are thinking of large-scale processing, then I recommend the third solution.

🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.lib.format.write_array_header_1_0.html
numpy.lib.format.write_array_header_1_0 — NumPy v2.2 Manual
Write the header for an array using the 1.0 format. ... This has the appropriate entries for writing its string representation to the header of the file.
🌐
w3tutorials
w3tutorials.net › blog › store-numpy-row-and-column-headers
How to Store Row and Column Headers in a NumPy 2D Array: NumPythonic Method for Dates and Stock Prices — w3tutorials.net
Performance: Numerical data stays in a fast, homogeneous array. Flexibility: Easily add/remove headers or data without redefining dtypes. Simplicity: Intuitive for 2D operations (e.g., prices.mean(axis=0) for average prices per ticker). Manual indexing: Requires tracking indices to link headers and data. While not pure NumPy, Pandas is built on NumPy and natively supports row/column labels via DataFrame objects.
🌐
NumPy
numpy.org › doc › 1.21 › reference › generated › numpy.lib.format.write_array_header_1_0.html
numpy.lib.format.write_array_header_1_0 — NumPy v1.21 Manual
Write the header for an array using the 1.0 format. ... This has the appropriate entries for writing its string representation to the header of the file.
🌐
Stack Overflow
stackoverflow.com › questions › 29926772 › putting-headers-into-an-array-python
csv - putting headers into an array, python - Stack Overflow
I would first read the irregular lines with normal python then, on the regular lines, use genfromtxt with skip_header and usecols (make a tuple like (i for i in range(2,102)) ... Sign up to request clarification or add additional context in comments.
🌐
TutorialsPoint
tutorialspoint.com › article › convert-a-numpy-array-to-pandas-dataframe-with-headers
Convert a NumPy array to Pandas dataframe with headers
May 30, 2023 - Let?s see the input-output scenarios to understand how to convert a NumPy array to a Pandas dataframe. Assuming we have a two-dimensional Numpy array with few values, and in the output, we will see a DataFrame with columns names. Input numpy array: [[1 2] [3 4]] Output DataFrame: header1 header2 0 1 2 1 3 4