Define dtypes in NumPy using a list?

I have a problem with NumPy dtypes. Essentially, I'm trying to create a table that looks like this (and then saves it using rec2csv):

name1 name2 name3 . . . name1 # # # name2 # # # name2 # # # . . . 

The matrix (a numerical array in the center) is already calculated before I try to add name tags. I tried using the following code:

  dt = dtype({'names' : tuple(blah), 'formats' : tuple(fmt)}) ReadArray = array(tuplelist, dtype=dt) 

where tuplelist is a list of strings (for example, the string [name1, #, #, # ...]), blah is a list of strings (that is, names, blah = ['name1', 'name2', ...] ) , and fmt is a list of formats, s (ie fmt = [str, float, float, ...] ).

The error I am getting is the following:

 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "table_calc_try2.py", line 152, in table_calc_try2 dt = dtype({'names' : tuple(blah), 'formats' : tuple(fmt)}) TypeError: data type not understood 

Can anyone help?

Thanks!

+3
python numpy
source share
1 answer

The following code may help:

 import numpy as np dt = np.dtype([('name1', '|S10'), ('name2', '<f8')]) tuplelist=[ ('n1', 1.2), ('n2', 3.4), ] arr = np.array(tuplelist, dtype=dt) print(arr['name1']) # ['n1' 'n2'] print(arr['name2']) # [ 1.2 3.4] 

Your immediate problem was that np.dtype expects format specifiers to be of the numpy type, such as '|S10' or '<f8' , and not Python types like str or float . If you type help(np.dtype) , you will see many examples of how np.dtypes can be specified. (I just mentioned a few.)

Note that np.array expects a list of tuples. This is pretty detailed.

The list of lists raises TypeError: expected a readable buffer object .

A (tuple of tuples) or (tuple of lists) raises ValueError: setting an array element with a sequence .

+12
source share

All Articles