我如何从函数填充一个numpy结构化数组? [英] How can I fill a numpy structured array from a function?

查看:76
本文介绍了我如何从函数填充一个numpy结构化数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用numpy创建了一个结构化数组.每个结构代表一个像素的rgb值.

I have created a structured array using numpy. Each structure represents the rgb value of a pixel.

我正在尝试找出如何从函数中填充数组,但我不断收到预期的可读缓冲区对象"错误.

I am trying to work out how to fill the array from a function but I keep getting an 'expected a readable buffer object' error.

我可以从函数中设置单个值,但是当我尝试使用'fromfunction'时会失败.

I can set individual values from my function but when I try to use 'fromfunction' it fails.

我从控制台复制了dtype.

I copied the dtype from the console.

有人可以指出我的错误吗?

Can anyone point out my mistake?

我必须使用3维数组而不是2d结构

Do I have to use a 3 dimensional array as opposed to a 2d of structures

import numpy as np

#define structured array
pixel_output = np.zeros((4,2),dtype=('uint8,uint8,uint8'))
#print dtype
print pixel_output.dtype

#function to create structure
def testfunc(x,y):
    return (x,y,x*y)

#I can fill one index of my array from the function.....
pixel_output[(0,0)]=testfunc(2,2)

#But I can't fill the whole array from the function
pixel_output = np.fromfunction(testfunc,(4,2),dtype=[('f0', '|u1'), ('f1', '|u1'), ('f2', '|u1')])

推荐答案

X=np.fromfunction(testfunc,(4,2))
pixel_output['f0']=X[0]
pixel_output['f1']=X[1]
pixel_output['f2']=X[2]
print pixel_output

产生

array([[(0, 0, 0), (0, 1, 0)],
       [(1, 0, 0), (1, 1, 1)],
       [(2, 0, 0), (2, 1, 2)],
       [(3, 0, 0), (3, 1, 3)]], 
      dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1')])

fromfunction返回由(4,2)数组组成的3个元素的列表.我依次将每个分配给pixel_output的3个字段.我将归纳给您.

fromfunction returns a 3 element list of (4,2) arrays. I assign each one, in turn, to the 3 fields of pixel_output. I'll leave the generalization to you.

另一种方式(将元组分配给元素)

Another way (assign a tuple to element)

for i in range(4):
    for j in range(2):
        pixel_output[i,j]=testfunc(i,j)

具有神奇的功能 http://docs.scipy.org/doc/numpy/reference/generation/numpy.core.records.fromarrays.html#numpy.core.records.fromarrays

pixel_output[:]=np.core.records.fromarrays(X)

当我查看fromarrays代码(使用Ipython ??)时,我发现它正在做我起初的工作-按字段分配字段.

When I look at the fromarrays code (with Ipython ??), I see it is doing what I did at first - assign field by field.

for i in range(len(arrayList)):
    _array[_names[i]] = arrayList[i]

这篇关于我如何从函数填充一个numpy结构化数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆