简体   繁体   English

如何使现有的numpy数组成为结构化数组?

[英]How can I make an existing numpy array a structured array?

I would like to give an existing numpy array named columns. 我想给一个现有的名为列的numpy数组。 I've tried to name the columns in the following way: 我尝试通过以下方式命名列:

X = np.random.normal(0,1,(3,3))
names = ['a','b','c']
types = ['f4']*len(names)
t = list(zip(names,types))

Y= np.array(X, dtype=t)

However, when I call Y['a'] , I am given a 3x3 array rather than the first column of X, which is 3x1. 但是,当我调用Y['a'] ,会得到3x3数组,而不是X的第一列3x1。

How can I give an existing array named columns? 如何给一个名为columns的现有数组? What is my error in my example? 我的示例中有什么错误?

You're looking for .view , which reinterprets existing memory in a new way. 您正在寻找.view ,它以一种新的方式重新解释了现有的内存。

names = ['a','b','c']
types = [X.dtype]*len(names)
t = list(zip(names,types))
Y = X.view(t)

For this to work, you need to match the dtype of X - f4 is probably not correct. 为此,您需要匹配X的dtype- f4可能不正确。

Your code is equivalent to X.astype(t) . 您的代码等效于X.astype(t) When converting to a struct array, that tries to set every field to the same value. 转换为结构数组时,它将尝试将每个字段设置为相同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM