gpt4 book ai didi

python - 混合类型的 NumPy 数组/矩阵

转载 作者:太空狗 更新时间:2023-10-29 20:15:40 24 4
gpt4 key购买 nike

我正在尝试创建一个具有混合数据类型(字符串、整数、整数)的 NumPy 数组/矩阵 (Nx3)。但是,当我通过添加一些数据来追加此矩阵时,出现错误:TypeError: invalid type promotion。请问,有人可以帮我解决这个问题吗?

当我使用示例数据创建数组时,NumPy 将矩阵中的所有列转换为一个“S”数据类型。而且我不能为数组指定数据类型,因为当我这样做时 res = np.array(["TEXT", 1, 1], dtype='S, i4, i4') - 我得到一个错误:TypeError: expected a readable buffer object

模板.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

最佳答案

您的问题出在数据上。试试这个:

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

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

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

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

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

这通常也很有用。

关于python - 混合类型的 NumPy 数组/矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24832715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com