Skip to content Skip to sidebar Skip to footer

How Can I Fill A Numpy Structured Array From A Function?

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

Solution 1:

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

produces

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 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)

And with the magical functiion http://docs.scipy.org/doc/numpy/reference/generated/numpy.core.records.fromarrays.html#numpy.core.records.fromarrays

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

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]

Post a Comment for "How Can I Fill A Numpy Structured Array From A Function?"