I am trying to work on a requirement where I am trying to see the data type of the structure array. Here is the code-
OrderDate = ['05-11-1996', '01-01-1971', '03-15-1969', '08-09-1983']
OrderAmount = [25.9, 44.8, 36.1, 29.4]
OrderNumber = [25, 45, 37, 19]
OrderName=['Ronaldo','Messi','Dybala','Pogba']
import numpy as np
data = np.zeros(3, dtype={'OrderDates':('OrderDate','OrderAmount', 'OrderNumber','OrderName'),
'formats':('U10','f8','i4','U10')})
print(data.dtype)
The Output should be:-
[('OrderDate', '<U10'), ('OrderAmount', '<f8'), ('OrderNumber', '<i4'), ('OrderName', '<U10')]
But i am getting an error-
ValueError Traceback (most recent call last)
<ipython-input-10-727f000630c8> in <module>()
1 import numpy as np
2 data = np.zeros(3, dtype={'OrderDates':('OrderDate','OrderAmount', 'OrderNumber','OrderName'),
----> 3 'formats':('U10','f8','i4','U10')})
4 print(data.dtype)
1 frames
/usr/local/lib/python3.7/dist-packages/numpy/core/_internal.py in _makenames_list(adict, align)
30 n = len(obj)
31 if not isinstance(obj, tuple) or n not in [2, 3]:
---> 32 raise ValueError("entry not a 2- or 3- tuple")
33 if (n > 2) and (obj[2] == fname):
34 continue
ValueError: entry not a 2- or 3- tuple
Can you please tell me where am i going wrong?
CodePudding user response:
The numpy.zeros() function returns a new array of given shape and type, with zeros.
Syntax:
numpy.zeros(shape, dtype = None, order = 'C')
You are using wrong syntax, it should looks like:
import numpy as np
data = np.zeros((2,), dtype=[('OrderDate','U10'),('OrderAmount','f8')
('OrderNumber','i4'),('OrderName','U10')]) # custom dtype
print(data.dtype)
[('OrderDate', '<U10'), ('OrderAmount', '<f8'), ('OrderNumber', '<i4'), ('OrderName', '<U10')]
CodePudding user response:
Use 'names' as the dict
key:
In [178]: data = np.zeros(3, dtype={'names':('OrderDate','OrderAmount', 'OrderNu
...: mber','OrderName'),
...: 'formats':('U10','f8','i4','U10')})
In [179]: data
Out[179]:
array([('', 0., 0, ''), ('', 0., 0, ''), ('', 0., 0, '')],
dtype=[('OrderDate', '<U10'), ('OrderAmount', '<f8'), ('OrderNumber', '<i4'), ('OrderName', '<U10')])
Though I usually use the list of tuples format, same as the default dtype
display.