Get recarray / columns python attributes

I am trying to get repeat column headers and run into serious problems. If I read in a CSV file using the pylab csv2rec function, I can access the column headers as follows:

from pylab import csv2rec
x = csv2rec(file.csv)
x.column1
x.column2

Where "column1" is the title of the first column, and it returns the rest of the values ​​in the column. But I read in a CSV file, where I do not know all the values ​​of the column names, and I want to have access to them (either skip or set the list). It seems to be easy. Any ideas?

+5
source share
1 answer

You can use x.dtype.names:

>>> import numpy as np

>>> a = np.array([0.1,0.2])
>>> b = np.array([0.3,0.4])
>>> dtype = {'names' : ['a','b'], 'formats' : ['f8', 'f8']}
>>> c = np.rec.fromarrays([a,b], dtype = dtype)
>>> c
rec.array([(0.1, 0.3), (0.2, 0.4)], 
      dtype=[('a', '<f8'), ('b', '<f8')])
>>> print c.dtype.names
('a', 'b')

Or using your example:

[physics@aurora ~/calc ]$ cat csv.dat 
a,b
0.1,0.3
0.2,0.4

In [1]: from pylab import csv2rec

In [2]: x = csv2rec('csv.dat')

In [3]: for name in x.dtype.names:
   ...:         print name
a
b
+7
source

All Articles