Skip to content Skip to sidebar Skip to footer

Define Dtypes In Numpy Using A List?

I just am having a problem with NumPy dtypes. Essentially I'm trying to create a table that looks like the following (and then save it using rec2csv): name1 name2 name3 .

Solution 1:

The following code might 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 the format specifiers to be numpy types, such as '|S10' or '<f8' and not Python types, such as str or float. If you type help(np.dtype) you'll see many examples of how np.dtypes can be specified. (I've only mentioned a few.)

Note that np.array expects a list of tuples. It's rather particular about that.

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

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

Post a Comment for "Define Dtypes In Numpy Using A List?"