Home > database >  Difference between np.dtype and np.dtype.name
Difference between np.dtype and np.dtype.name

Time:10-07

As stated in the title, I am willing to know the difference between np.dtype and np.dtype.name. When I used them, I found that they provide same output like below:

dt = np.array([[(1, 5, 2), (2, 4.0, 7)], [(6, 4, 2), (2, 8, 10)]])
print('\nData type of array elements:', dt.dtype)
print('\nName of data type:', dt.dtype.name)

Output is

Data type of array elements: float64

Name of data type: float64

CodePudding user response:

If you print an object it asks the object what to print i.e. it calls it's "repr" method. Python objects always have that but you can define them yourself. E.g.

class foo:
    def __init__(self):
        pass

print(foo())

gives me <__main__.foo object at 0x10b737280>

while

class foo:
    def __init__(self):
        pass

    def __repr__(self):
        return "__repr__"

print(foo())

gives me __repr__.

So an object of numpy type float64 has two methods that give you the name. One for you to call by hand and one for python to call implicitly if you asking for a string representation of the object e.g. if you print it.

You can see that more clearly like this

dt = np.array([[(1, 5, 2), (2, 4.0, 7)], [(6, 4, 2), (2, 8, 10)]])
print('Type of data type of array elements:', type(dt.dtype))
print('Type of name of data type:', type(dt.dtype.name)).

It gives you

Type of data type of array elements: <class 'numpy.dtype[float64]'>
Type of name of data type: <class 'str'>

CodePudding user response:

In [62]: arr = np.array([[(1, 5, 2), (2, 4.0, 7)], [(6, 4, 2), (2, 8, 10)]])
In [63]: arr
Out[63]: 
array([[[ 1.,  5.,  2.],
        [ 2.,  4.,  7.]],

       [[ 6.,  4.,  2.],
        [ 2.,  8., 10.]]])

For this simple dtype, the name is the same as the str/print representation.

In [64]: arr.dtype
Out[64]: dtype('float64')      # the repr print
In [65]: arr.dtype.name
Out[65]: 'float64'
In [66]: print(arr.dtype)
float64

But it's possible to construct more complex dtypes where the name and the display are different. For example, since your constructor has inner tuples, I can create an array with a compound dtype, a structured array:

In [69]: arr = np.array([[(1, 5, 2), (2, 4.0, 7)], [(6, 4, 2), (2, 8, 10)]], dtype='i,f,f8')
In [70]: arr
Out[70]: 
array([[(1, 5.,  2.), (2, 4.,  7.)],
       [(6, 4.,  2.), (2, 8., 10.)]],
      dtype=[('f0', '<i4'), ('f1', '<f4'), ('f2', '<f8')])
In [71]: arr.dtype
Out[71]: dtype([('f0', '<i4'), ('f1', '<f4'), ('f2', '<f8')])
In [72]: arr.dtype.name
Out[72]: 'void128'
In [73]: arr.dtype.fields
Out[73]: 
mappingproxy({'f0': (dtype('int32'), 0),
              'f1': (dtype('float32'), 4),
              'f2': (dtype('float64'), 8)})
  • Related