设置名称时使用numpy.ones创建的意外大数组 [英] Unexpectedly large array created with numpy.ones when setting names
问题描述
我正在尝试使用下面的numpy代码获取10 x 8 array
Im trying to get a 10 x 8 array
using the code below with numpy
import numpy as np
columns = ["Port Wt", "Bench Wt", "Port Retn",
"Bench Retn", "Attrib", "Select", "Inter", "Total"]
a = np.ones([10,len(columns)],
dtype={"names":columns, "formats":["f8"]*len(columns)})
我是numpy的新手,但是我遇到了意外的行为-我得到的是10 x 8 x 8 grid
.
I'm new to numpy and I get unexpected behaviour - I'm getting a 10 x 8 x 8 grid
instead.
我尝试过
a.dtype.names = columns
并获得一个ValueError: there are no fields defined
我在做什么错了,我怎么会得到一个带有名称的10 x 8网格?
What am I doing wrong and how would I get a 10 x 8 grid as desired with the names?
谢谢
推荐答案
您的代码确实会生成10 x 8
数组,即a.shape == (10, 8)
.但是,数组中的每个元素都有8个字段,总共增加了10 x 8 x 8
个字段.
Your code does produce a 10 x 8
array, i.e. a.shape == (10, 8)
. However, each element in the array has 8 fields, adding to a total of 10 x 8 x 8
fields.
所以您可能想要的是一个形状为(10,)
且每个元素有8个字段的数组:
So what you probably want is an array with shape (10,)
and 8 fields per element:
a = np.ones((10,), dtype={"names":columns, "formats":["f8"]*len(columns)})
这篇关于设置名称时使用numpy.ones创建的意外大数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!