NumPy混合类型的数组/矩阵

Vit*_*t D 10 python arrays numpy matrix

我正在尝试使用混合数据类型(字符串,整数,整数)创建NumPy数组/矩阵(Nx3).但是当我通过添加一些数据来附加这个矩阵时,我收到一个错误:TypeError:无效的类型提升.拜托,有人可以帮我解决这个问题吗?

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

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)
Run Code Online (Sandbox Code Playgroud)

输出:

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

 Array example:
 array(['TEXT', '1', '1'], dtype='|S4')
Run Code Online (Sandbox Code Playgroud)

错误:

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
Run Code Online (Sandbox Code Playgroud)

DrV*_*DrV 9

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

res = np.array(("TEXT", 1, 1), dtype='|S4, i4, i4')
Run Code Online (Sandbox Code Playgroud)

要么

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

数据必须是元组或元组列表.从错误信息中不太明显,是吗?

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

res = np.array([("TEXT", 1, 1), ("XXX", 2, 2)], dtype='object, i4, i4')
Run Code Online (Sandbox Code Playgroud)

这通常也非常有用.


sir*_*ark 5

如果你不喜欢 numpy,那么Pandas DataFrame是完美的选择。或者,您可以将数组中的字符串字段指定为 python 对象(以 dtype='O, i4, i4' 为例)。另外 append 似乎喜欢元组列表,而不是列表列表。我认为这与列表的可变性有关,不确定。