HOW TO CREATE ARRAY USING NUMPY IN PYTHON?

The array object in NumPy is called ndarray.

We can create a NumPy ndarray object by using the array() function. We can pass a list, tuple or any array-like object into the array() method, and it will be converted into an ndarray.

import numpy as np

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

print(arr)

print(type(arr))

type(): It is a built-in Python function which returns the type of the object passed to it. Like in above code it shows that arr is numpy.ndarray type.

Output

[1 2 3]
<class 'numpy.ndarray'>

What is a 0 – D Array?

0 – D Arrays-

The 0-D arrays in a NumPy are the elements in an array. Each value in an array is a 0-D array.

import numpy as np
arr=np.array(5)
print(arr)

It will create a 0-D array with value 5

5

1-D Arrays in Python NumPy

1-D or unidimensional array is an array having 0-D arrays as its elements.

Example of 1-D Array using Python NumPy

import numpy as np

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

print(arr)

Output-

[1 2 3 4]

2-D Arrays

2-D array is an array having 1-D arrays as its elements. 2-D arrays can be used to represent matrix.

Example of 2-D Array using Python NumPy

import numpy as np

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

print(arr)

Output-

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

3-D arrays

3-D array is an array having 2-D arrays as its elements.

Example of 3-D Array using Python NumPy

import numpy as np

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

print(arr)

Output

[[[1 2]
  [3 4]]

 [[1 2]
  [3 4]]]

How to check no. of Dimensions?

ndim attribute in Python NumPy returns an integer equal to the no. of the dimensions the array have.

import numpy as np

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

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

Output

0
1
2
3

N-Dimensional Array

An array can have any no. of dimensions and by using ndmin argument in array() we can define the no. of dimension of array.

import numpy as np

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

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

Output

[[[1 2 3]]]
number of dimensions : 3

Posted

in

Tags:

Comments

Leave a Reply