Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy - assign column data types (dtype) to existing array

I have a given array:

array = [(u'Andrew', -3, 3, 100.032) (u'Bob', -4, 4, 103.323) (u'Joe', -5, 5, 154.324)]

that is generated from another process (that I cannot control) of taking a CSV table and it outputs this numpy array. I now need to assign the dtypes of the columns to do further analysis.

How can I do this?

Thank you

like image 601
code base 5000 Avatar asked Dec 25 '22 06:12

code base 5000


2 Answers

Is this what you need ?

new_array = np.array(array, dtype = [("name", object), 
                                     ("N1", int), 
                                     ("N2", int),
                                     ("N3", float)])

where name and N1-3 are column names I gave.

It gives :

array([(u'Andrew', -3, 3, 100.032), (u'Bob', -4, 4, 103.323),
       (u'Joe', -5, 5, 154.324)], 
      dtype=[('name', 'O'), ('N1', '<i8'), ('N2', '<i8'), ('N3', '<f8')])

You can sort on "N1" for instance :

new_array.sort(order="N1")
new_array
array([(u'Joe', -5, 5, 154.324), (u'Bob', -4, 4, 103.323),
       (u'Andrew', -3, 3, 100.032)], 
      dtype=[('name', 'O'), ('N1', '<i8'), ('N2', '<i8'), ('N3', '<f8')])

Hope this helps.

like image 66
jrjc Avatar answered Dec 28 '22 14:12

jrjc


recarr = np.rec.fromrecords(array)

Optionally set field names:

recarr = np.rec.fromrecords(array, names="name, idata, idata2, fdata")
like image 38
Stefan Avatar answered Dec 28 '22 15:12

Stefan