Explore array(), type() and astype() functions
What is ndarray in Numpy?
"ndarray" stands for n-dimensional array. Numpy creates an object for an array in this type.
How to create an array in Numpy?
We can create an array using the built-in Numpy function called numpy.array() function.
Example
import numpy as np
array_1 = np.array([1,2,3,4,5,6], dtype='i', ndmin=0)
print(array_1)
Output
[1 2 3 4 5 6]
In the above example, we create an array with list of object, integer datatype and number of dimensions.
type() function
It is used to show the type of the object passed in it.
Example
print(type(array_1))
Output
<class 'numpy.ndarray'>
astype() function
It is used to create a copy of an particular array with specified datatype.
Example
array_2 = array_1.astype(dtype='f')
print(array_2)
Output
[1. 2. 3. 4. 5. 6.]
Note: Some of the datatypes are integer('i'), float('f'), boolean('b') and string('S').
Some of the attributes of Numpy
Example
print("Array 1 - dtype, ndim, nbytes")
print(array_1.dtype)
print(array_1.ndim)
print(array_1.nbytes)
print("Array 2 - dtype, ndim, nbytes")
print(array_2.dtype)
print(array_2.ndim)
print(array_2.nbytes)
Output
Array 1 - dtype, ndim, nbytes
int32
1
24
Array 2 - dtype, ndim, nbytes
float32
1
24
Pro tip: Google Colaboratory is a cloud platform makes us easy to use and run anywhere.
Follow on LinkedIn - Trillionaire TK
Follow on Instagram - Trillionaire TK
Visit our website - Information Technology
Learn, Code, Practice!!!