gpt4 book ai didi

python - 将数组的数组转换为 NumPy 的 ndarray of ndarrays

转载 作者:太空宇宙 更新时间:2023-11-04 05:44:35 26 4
gpt4 key购买 nike

我一直在尝试用 ndarrays 的 numpy ndarray 转换数组数组。

这是我的数据类型:

dt = 'i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,f8,i8,i8,f8,f8,f8,a50,a50,a50,a50'

这是我的数据:

# data array reduced to one row for sake of readability
data = [[45608L, 0L, 46115L, 11952L, 11952L, 0, 0, 0, 0, 0, 11951L, 11951L, 46176L, 9.0, 0, 1, 1407340577.0, 1407340577.0, 0, 'Simulation Movement', 'planned', '', ''],]

我已经尝试过这些方法:

np.array(data, dt)
np.array([np.array(row, dt) for row in data])

但是当我运行这两个时,我得到:

TypeError:需要一个可读的缓冲区对象

Buuuuut,如果我调用 np.array 时使用的数组仅包含行中的每个元素并使用适当的数据类型(这是使用带有枚举的循环和拆分 dt ) ,它有效。是这样的:

for row in data:
for index, value in enumerate(row):
np.array([value,], dt.split(',')[index])

有什么想法吗?

最佳答案

似乎要使它起作用,您需要将内部列表转换为元组。示例 -

import numpy as np

dt = 'i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,f8,i8,i8,f8,f8,f8,a50,a50,a50,a50'

data = [[45608L, 0L, 46115L, 11952L, 11952L, 0, 0, 0, 0, 0, 11951L, 11951L, 46176L, 9.0, 0, 1, 1407340577.0, 1407340577.0, 0, 'Simulation Movement', 'planned', '', ''],]

result = np.array(map(tuple, data),dt)

演示运行 here 。但是有了这个,你会得到一个包含 1 个元素的数组 shape = (1,)(第 1 个元素是元组)。


你也可以使用'object'作为数据类型,Example -

result1 = np.array(data,'object')

即使这确实会生成一个具有正确形状的数组,但由于混合类型,有些事情可能无法正常工作(但我猜你希望如此)。

关于python - 将数组的数组转换为 NumPy 的 ndarray of ndarrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32784764/

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