0

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.

1
  • Why not just declare a with dtype=l? Otherwise your float values will get coerced to strings. Commented Aug 26, 2019 at 18:38

1 Answer 1

1
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')])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.