Loading, please wait...

A to Z Full Forms and Acronyms

What are NumPy Data Types |part-3

Aug 10, 2020 NumPy , Data Types , dtype, astype() , 3776 Views
This article is about NumPy data types. How to check datatypes of array ? How to convert datatype on existing array?

                                     NumPy Data types

Before getting into this article, we would suggest you read an article on DATA TYPES in Python for a better understanding of data types. NumPy has extra Data types. In NumPy, the data types are represented with one character.

Let’s see what are characters that represent the NumPy data types.

So, here is the list of all data types in NumPy & the characters used to represent them.

 

  • b –Boolean
  • c – Complex Float
  • f - float
  • i –integer
  • m –timedelta
  • M –data time
  • O –object
  • S- string
  • u –unsigned integer
  • U-Unicode string
  • V – a fixed chunk of memory for other types (void)

How to check the data type of an Array?

NumPy has a property named dtype that returns the data type of a Numpy array. Let’s look at an example.

import numpy as np

ar1= np.array([10,20,30,40,50])

print(ar1.dtype)
#output:int32

ar2= np.array(['a', 'b', 'c'])

print((ar2.dtype))

#output:<U1
ar3= np.array([True, False, True])

print(ar3.dtype)
#output:bool

ar4= np.array([1.0,2.8,3.9,40,50])

print(ar4.dtype)
#output: float64

 

Note: we use array() function to create a Numpy array, this function has can take an optional argument: dtype . this allows us to specify the expected data type of the passed array.

import numpy as np

ar2= np.array(['a', 'b', 'c'],dtype='S')

print(ar2)

print((ar2.dtype))

#output: [b'a' b'b' b'c']

|S1

Note:

We can also specify the size of the data type. For i, u, f, S, & U

We can define the size as well.

import numpy as np
ar2= np.array(['3', '2', '1'],dtype='i4')

print(ar2)
#output:[3 2 1]

print((ar2.dtype))

#output: int32

How to convert Data Type on Existing Arrays?

Using the astype() function, we can convert data type on the existing array. This function creates a copy of the array & allows us to specify the data type as a parameter.

Example:

import numpy as np

arr = np.array([11.5, 12.9, 13.8])

newarr= arr.astype('i')

print(newarr)
#output: [11 12 13]


print(newarr.dtype)
#output:#int32



The data type is always defined using a string like ‘i’ for integer or we can also specify data type directly like int for integer. 

Example

import numpy as np

arr = np.array([11.5, 12.9, 13.8])

newarr= arr.astype(int)

print(newarr)
#output:[11 12 13]



print(newarr.dtype)
#output: int64

 

 

 

Thank you so much for reading this article, I just hope you like the content… if you find it useful then don’t forget to share and comment...  

More is yet to come!

Till now,

Happy learning

A to Z Full Forms and Acronyms

Related Article