Arrays in NumPy

What are arrays in numPy and how to use it?

In NumPy, an array is a powerful data structure that allows you to store and manipulate numerical data efficiently. It is called a NumPy array or ndarray (N-dimensional array).

Creating a NumPy Array

To create an array, you first need to import NumPy:

import numpy as np
  1. Creating Arrays from Lists You can create a NumPy array from a Python list using np.array():
arr = np.array([1, 2, 3, 4, 5])
print(arr)
# Output: [1 2 3 4 5]
  1. Creating Multi-Dimensional Arrays You can create a 2D (matrix) or higher-dimensional array:
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr_2d)

Output:

[[1 2 3]
 [4 5 6]]
  1. Using NumPy Functions to Create Arrays NumPy provides several functions to generate arrays:
  • Zeros Array:
    zeros = np.zeros((3, 3))  # 3x3 array of zeros
    
  • Ones Array:
    ones = np.ones((2, 4))  # 2x4 array of ones
    
  • Identity Matrix:
    identity = np.eye(3)  # 3x3 identity matrix
    
  • Random Array:
    rand_arr = np.random.rand(2, 3)  # 2x3 array with random values
    
  • Arange (Like Python range):
    arr = np.arange(0, 10, 2)  # [0, 2, 4, 6, 8]
    
  • Linspace (Evenly Spaced Values):
    lin_arr = np.linspace(0, 10, 5)  # [0, 2.5, 5, 7.5, 10]
    

NumPy Array Properties

You can check the following properties of an array:

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

print(arr.shape)  # (2, 3) -> Rows x Columns
print(arr.ndim)   # 2 -> Number of dimensions
print(arr.size)   # 6 -> Total elements
print(arr.dtype)  # int64 (or int32) -> Data type of elements
No questions available.