混合类型的 NumPy 数组/矩阵 [英] NumPy array/matrix of mixed types

查看:34
本文介绍了混合类型的 NumPy 数组/矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用混合数据类型(字符串、整数、整数)创建一个 NumPy 数组/矩阵 (Nx3).但是当我通过添加一些数据来附加这个矩阵时,我收到一个错误:TypeError: invalid type Promotion.请问有人能帮我解决这个问题吗?

I'm trying to create a NumPy array/matrix (Nx3) with mixed data types (string, integer, integer). But when I'm appending this matrix by adding some data, I get an error: TypeError: invalid type promotion. Please, can anybody help me to solve this problem?

当我用样本数据创建一个数组时,NumPy 将矩阵中的所有列转换为一个S"数据类型.而且我无法为数组指定数据类型,因为当我这样做时 res = np.array(["TEXT", 1, 1], dtype='S, i4, i4')- 我收到一个错误:TypeError:需要一个可读的缓冲区对象

When I create an array with the sample data, NumPy casts all columns in the matrix to the one 'S' data type. And I can't specify data type for an array, because when i do this res = np.array(["TEXT", 1, 1], dtype='S, i4, i4') - I get an error: TypeError: expected a readable buffer object

templates.py

import numpy as np
from pprint import pprint

test_array = np.zeros((0, 3), dtype='S, i4, i4')
pprint(test_array)

test_array = np.append(test_array, [["TEXT", 1, 1]], axis=0)
pprint(test_array)

print("Array example:")
res = np.array(["TEXT", 1, 1])
pprint(res)

输出:

array([], shape=(0L, 3L), 
  dtype=[('f0', 'S'), ('f1', '<i4'), ('f2', '<i4')])

 Array example:
 array(['TEXT', '1', '1'], dtype='|S4')

错误:

Traceback (most recent call last):

File "templates.py", line 5, in <module>
test_array = np.append(test_array, [["TEXT", 1, 1]], axis=0)

File "lib\site-packages\numpy\lib\function_base.py", line 3543, in append
return concatenate((arr, values), axis=axis)

TypeError: invalid type promotion

推荐答案

你的问题出在数据上.试试这个:

Your problem is in the data. Try this:

res = np.array(("TEXT", 1, 1), dtype='|S4, i4, i4')

res = np.array([("TEXT", 1, 1), ("XXX", 2, 2)], dtype='|S4, i4, i4')

数据必须是元组或元组列表.从错误消息来看不是很明显,是吗?

The data has to be a tuple or a list of tuples. Not quite evident form the error message, is it?

另外请注意,要真正保存文本数据,必须指定文本字段的长度.如果要将文本保存为对象(仅在数组中引用,则:

Also, please note that the length of the text field has to be specified for the text data to really be saved. If you want to save the text as objects (only references in the array, then:

res = np.array([("TEXT", 1, 1), ("XXX", 2, 2)], dtype='object, i4, i4')

这通常也很有用.

这篇关于混合类型的 NumPy 数组/矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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