如何构造嵌套的numpy记录数组?

2024-06-11 14:24:45 发布

您现在位置:Python中文网/ 问答频道 /正文

numpy manual提到了numpy.save的用例

Annie Analyst has been using large nested record arrays to represent her statistical data.

是否有可能没有dtype=object的嵌套记录数组?如果是,怎么办?在


Tags: tonumpysavemanual用例recordnestedhas
2条回答

可以按照构造嵌套列表的方式构造嵌套数组:

nested_list = [['a',1],['b',2],['c',3]]

import numpy as np
nested_array = np.array(nested_list)

是的,就像这样:

engine_dt = np.dtype([('volume', float), ('cylinders', int)])
car_dt = np.dtype([('color', int, 3), ('engine', engine_dt)])  # nest the dtypes

cars = np.rec.array([
    ([255, 0, 0], (1.5, 8)),
    ([255, 0, 255], (5, 24)),
], dtype=car_dt)

print(cars.engine.cylinders)
# array([ 8, 24])

在这里,np.dtype函数并不是绝对必要的,但它通常是一个好主意,并且相对于每次让array调用它,它的速度有了小幅度的提高。在

注意,rec.array在这里只需要使用.engine符号。如果您使用普通的np.array,那么您应该使用cars['engine']['cylinders']

相关问题 更多 >