使用列表在NumPy中定义dtypes? [英] Define dtypes in NumPy using a list?

查看:87
本文介绍了使用列表在NumPy中定义dtypes?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是遇到了NumPy dtypes的问题.本质上,我正在尝试创建一个如下所示的表(然后使用rec2csv保存该表):

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 . . . 
name1  #       #      #
name2  #       #      #
name2  #       #      #
.
.
.

在尝试添加名称标签之前,已经计算出矩阵(位于中心的数字数组).我尝试使用以下代码:

The matrix (numerical array in the center), is already computed before I attempt to add the name tags. I've tried to use the following code:

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

其中tuplelist是行列表(即行[name1,#,#,#...]),blah是字符串列表(即名称blah = ['name1', 'name2', ...]),而fmt是格式列表,s(即fmt = [str, float, float, ...]).

where tuplelist is a list of rows (i.e. the row [name1, #, #, #...]), blah is a list of strings (i.e. the names, blah = ['name1', 'name2', ...]) and fmt is the list of format,s (i.e. fmt = [str, float, float, ...]).

我得到的错误如下:

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

任何人都可以帮忙吗?

谢谢!

推荐答案

以下代码可能会有所帮助:

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]

您的直接问题是np.dtype期望格式说明符为numpy类型,例如'|S10''<f8',而不是Python类型,例如strfloat.如果键入help(np.dtype),您将看到许多有关如何指定np.dtypes的示例. (我只提到了一些.)

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.)

请注意,np.array需要一个元组列表.这是相当特别的.

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

列表列表会引发TypeError: expected a readable buffer object.

一个(元组的元组)或一个(列表的元组)引发ValueError: setting an array element with a sequence.

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

这篇关于使用列表在NumPy中定义dtypes?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆