Reputation: 980
I tried to run the following python code.
import numpy as np
recarr = np.zeros((2,), dtype=('i4,f4,a10'))
col1 = np.arange(1,3)
col2 = np.arange(4,6, dtype=np.float32)
col3 = ['Man', 'Woman']
tmp = zip(col1, col2, col3)
recarr[:] = tmp
But I had the following error message.
File "<ipython-input-55-0c1735078108>", line 1, in <module>
recarr[:] = tmp
ValueError: setting an array element with a sequence.
Could you please help me to solve this problem? Thank you.
Upvotes: 0
Views: 153
Reputation: 95993
The zip
function returns an iterator. To properly assign it to a slice you must materialize the iterator:
>>> recarr[:] = list(tmp)
>>> recarr
array([(1, 4., b'Man'), (2, 5., b'Woman')],
dtype=[('f0', '<i4'), ('f1', '<f4'), ('f2', 'S10')])
Note, if you don't want to materialize the iterator into a wasteful intermediate data-structure, you can use np.fromiter
:
>>> recarr = np.fromiter(tmp, dtype=('i4,f4,a10'), count=2)
>>> recarr
array([(1, 4., b'Man'), (2, 5., b'Woman')],
dtype=[('f0', '<i4'), ('f1', '<f4'), ('f2', 'S10')])
>>>
Note, I passed the count
argument, which is optional, but if you can provide a count
argument, it will make this constructor much more efficient.
Upvotes: 2