Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding row/column headers to NumPy arrays

I have a NumPy ndarray to which I would like to add row/column headers.

The data is actually 7x12x12, but I can represent it like this:

  A=[[[0, 1, 2, 3, 4, 5],       [1, 0, 3, 4, 5, 6],       [2, 3, 0, 5, 6, 7],       [3, 4, 5, 0, 7, 8],       [4, 5, 6, 7, 0, 9],       [5, 6, 7, 8, 9, 0]]        [[0, 1, 2, 3, 4, 5],       [1, 0, 3, 4, 5, 6],       [2, 3, 0, 5, 6, 7],       [3, 4, 5, 0, 7, 8],       [4, 5, 6, 7, 0, 9],       [5, 6, 7, 8, 9, 0]]] 

where A is my 2x6x6 array.

How do I insert headers across the first row and the first column, so that each array looks like this in my CSV output file?

        A, a, b, c, d, e, f          a, 0, 1, 2, 3, 4, 5,         b, 1, 0, 3, 4, 5, 6,         c, 2, 3, 0, 5, 6, 7,         d, 3, 4, 5, 0, 7, 8,         e, 4, 5, 6, 7, 0, 9,         f, 5, 6, 7, 8, 9, 0 

Right now, what I have done is made the array 7x13x13 and inserted the data such that I have a row and column of zeros, but I'd much prefer strings.

I guess I could just write an Excel macro to replace the zeros with strings. However, the problem is that NumPy cannot convert string to float, if I try to reassign those zeros as the strings I want.

like image 679
emmagras Avatar asked Jun 19 '12 17:06

emmagras


1 Answers

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     
like image 84
bmu Avatar answered Sep 19 '22 18:09

bmu