Parsley Man
Parsley Man

Reputation: 1

How to use a numpy array with fromiter

I tried to use a numpy array with fromiter but It gave this error

import numpy
l=numpy.dtype([("Ad","S20"),("Yas","i4"),("Derecelendirme","f")])
a=numpy.array([("Dr.Wah",20,0.9)])
d=numpy.fromiter(a,dtype=l,count=3)
print(d)

ValueError: setting an array element with a sequence.

Upvotes: 0

Views: 83

Answers (1)

hpaulj
hpaulj

Reputation: 231425

In [172]: dt=np.dtype([("Ad","S20"),("Yas","i4"),("Derecelendirme","f")]) 
     ...: alist = [("Dr.Wah",20,0.9)]   

The normal way to define a structured array is to use a list of tuples for the data along with the dtype:

In [173]: np.array( alist, dtype=dt)                                                                         
Out[173]: 
array([(b'Dr.Wah', 20, 0.9)],
      dtype=[('Ad', 'S20'), ('Yas', '<i4'), ('Derecelendirme', '<f4')])

fromiter works as well, but isn't as common

In [174]: np.fromiter( alist, dtype=dt)                                                                      
Out[174]: 
array([(b'Dr.Wah', 20, 0.9)],
      dtype=[('Ad', 'S20'), ('Yas', '<i4'), ('Derecelendirme', '<f4')])

If you create an array without the dtype:

In [175]: a = np.array(alist)                                                                                
In [176]: a                                                                                                  
Out[176]: array([['Dr.Wah', '20', '0.9']], dtype='<U6')
In [177]: _.shape                                                                                            
Out[177]: (1, 3)

a.astype(dt) does not work. You have to use a recfunction:

In [179]: import numpy.lib.recfunctions as rf                                                                
In [180]: rf.unstructured_to_structured(a, dtype=dt)                                                         
Out[180]: 
array([(b'Dr.Wah', 20, 0.9)],
      dtype=[('Ad', 'S20'), ('Yas', '<i4'), ('Derecelendirme', '<f4')])

Upvotes: 1

Related Questions