Professional Documents
Culture Documents
Prev
Next
If you do not have numpy installed in your system �rst you need to install it.
Python3
Prev A list in Python is a linear data structure that can hold heterogeneous elements they do not require to be declared
and are �exible to shrink and grow. On the other hand, an array is a data structure which can hold homogeneous
Next elements, arrays are implemented in Python using the NumPy library. Arrays require less memory than list.
The similarity between an array and a list is that the elements of both array and a list can be identi�ed by its index
value.
Python3
import numpy as np
l=[2,3,4,5]
print(l)
print(type(l))
print()
arr=np.array(l)
print(arr)
print(type(arr))
Output:
[2, 3, 4, 5]
<class 'list'>
[2 3 4 5]
<class 'numpy.ndarray'>
So we have �rst printed the list and then converted the list to an array and displayed that as well
Prev
Next
Syntax : numpy.ndarray.ndim(arr)
Parameters :
arr : [array_like] Input array. If it is not already an ndarray, a conversion is attempted.
Python3
a=np.array([1,2,3,4])
b=np.array([[1,2,3,4],[5,6,7,8]])
print(a.ndim)
print(b.ndim)
Output:
1
2
Prev
Next
Now we have few more functions such as np.array.shape, np.array.size and np.array.dtype
shape will basically return us the total number of rows and columns of the array in a tuple format (number of rows,
number of columns)
number of columns)
size will tell us the total number of elements or values present in the array
dtype will tell us the data type of values which the array is containing
Python3
b=np.array([[1,2,3,4],[5,6,7,8]])
print(b.shape)
print(b.size)
print(b.dtype)
Output:
(2, 4)
8
int32
Prev
• So we have 2 rows and 4 columns in the array b
Next
• We have 8 elements present in the array
• The data type of the elements present in the array is int
The numpy.zeros() function returns a new array of given shape and type, with zeros. Syntax:
Parameters :
Returns :
Python3
print("\nMatrix a : \n", a)
c = geek.zeros([3, 3])
print("\nMatrix c : \n", c)
Output :
Matrix b :
[0 0]
Matrix a :
[[0 0]
[0 0]]
Matrix c :
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
The numpy.ones() function returns a new array of given shape and type, with ones.
Prev
Parameters :
Returns :
Python3
Output :
Matrix b :
[1 1]
Matrix a :
[[1 1]
[1 1]]
Matrix c :
[[ 1. 1. 1.]
[ 1. 1. 1.]
[ 1. 1. 1.]]
Prev
Next