How To Create Arrays With Numpy

Create Numpy Array:

 Numpy is used to work with Arrays

Array can be of different Dimensions like 0D,1D,2D

In this lesson we will work with different dimensions array with the Numpy package

0D Array:

Example

Create a 0-D array with value 51

import numpy as np

arr = np.array(51)

print(arr)

Output: 51


1D Array:

An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.

These types of arrays are the most common types of arrays

Example


Let's Create a 1-D array containing the values like 4,7,9,11,12

Let's try to print the array now

import numpy as np

arr = np.array([4,7,9,11,12])

##########Here we are storing the array values in the array called arr

print(arr)

Output:

[4,7,9,11,12]



2-D Arrays:

An array that has the elements in the form of 1-D arrays is called a 2-D array.

These types of 2D arrays are often used to represent matrix or 2nd order tensors.

NumPy has dedicated sub module called as numpy.mat for the matrix operations


Example


Now let's create a 2-D array containing two 1D arrays with the values 4,5,6 and 7,8,9:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr)

Here the ouput will be the values in the 2D Array called arr

Output

[[1 2 3]
 [4 5 6]]



3-D arrays:

An array that has the elements in the form of 2-D arrays is called a 3-D array.

These types of 3D arrays are often used to represent the 3rd order tensors.

Example


Now let's create a 3-D array containing two 2D arrays both contains the values like 1,2,3 and 4,5,6

import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(arr)

Here the ouput will be the values in the 3D Array called arr

Output

[[[1 2 3]
  [4 5 6]]

 [[1 2 3]
  [4 5 6]]]


Check Number of Dimensions?

NumPy Arrays contains the ndim attribute that returns an integer value that shows how many dimensions the array have 


Example


Now let's check how many dimensions we are having in the array

import numpy as np

a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)

Output:

0
1
2
3


Higher Dimensional Arrays


An array can have any number of dimensions in it 

with the ndmin attribute you can mention the number of dimensions of the array

Example

Let's create an array with 5 dimensions and we can verify the dimension of the array

import numpy as np

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)

print('number of dimensions :', arr.ndim)

Output:

[[[[[1 2 3 4]]]]]

number of dimensions : 5






Comments