29 Mar Datatypes in Numpy
Python Numpy supports the following data types:
- b – boolean
- u – unsigned integer
- f – float
- c – complex float
- m – timedelta
- M – datetime
- O – object
- S – string
- U – unicode string
Let us see some examples:
- Get the datatype of a NumPy array with integers
- Get the datatype of a NumPy array with strings
- Set the datatype size within a NumPy array
- Convert one datatype to another
Get the datatype of a Numpy array with integers
To get the datatype of a Numpy array, use the dtype attribute. Let us see an example:
1 2 3 4 5 6 |
import numpy as np n = np.array([10, 20, 30]) print(n.dtype) |
Output
1 2 3 |
int32 |
Get the datatype of a Numpy array with strings
To get the datatype of a Numpy array, use the dtype attribute. Let us see an example:
1 2 3 4 5 6 |
import numpy as np n = np.array(["amit", "rohit", "ashwin", "jadeja", "virat"]) print(n.dtype) |
Output
1 2 3 |
<U6 |
Set the datatype size within a Numpy array
Set a defined data type to a new array using the dtype attribute. With that set the size as well. Let us see an example:
1 2 3 4 5 6 |
import numpy as np n = np.array(['amit', 'rohit', 'ashwin', 'jadeja', 'virat'], dtype='S5') print(n.dtype) |
Output
1 2 3 |
|S5 |
In the above example, we have set the data type as string and size 5.
Convert one datatype to another
Use the astype() to create a copy of an array and then set the new data type. This is how you can convert one type to another.
In the example, we have an array of strings. We will convert it to an integer, with i as a parameter as shown below:
1 2 3 4 5 6 7 8 9 10 11 |
import numpy as np n = np.array(['10', '20', '30', '40', '50']) print(n) print(n.dtype) n2 = n.astype('i') print(n2) print(n2.dtype) |
Output
1 2 3 4 5 6 |
['10' '20' '30' '40' '50'] <U2 [10 20 30 40 50] int32 |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments