Numpy Arrays in Python

Python : Numpy Arrays

What is Numpy Arrays?

Numpy stands for Numerical Python, and it is a library used for numerical computing with Python. One of the main features of numpy is its ndarray, which is an N-dimensional array object that provides a fast and efficient way of working with large datasets.

Creating Numpy Arrays:

To create a numpy array, we first need to import the numpy library.

import numpy as np

Now, we can create an array in various ways:

  • From a Python List:

    arr = np.array([1, 2, 3, 4, 5])
    print(arr) # Output: [1 2 3 4 5]
    
    arr = np.array([[1, 2, 3], [4, 5, 6]])
    print(arr) # Output [[1 2 3] [4 5 6]]
    
    
  • Using Built-in Functions:

    
    # Creating an array of zeros
    arr_zeros = np.zeros((2, 3))
    print(arr_zeros)
    
    # Output
    # [[0. 0. 0.]
    # [0. 0. 0.]]
    
    # Creating an array of ones
    arr_ones = np.ones((2, 3))
    print(arr_ones)
    
    # Output
    # [[1. 1. 1.]
    # [1. 1. 1.]]
    

Numpy Array Attributes:

Once we have created a numpy array, we can access its various attributes.

arr = np.array([1, 2, 3, 4, 5])
print(arr.shape)
print(arr.ndim)
print(arr.size)
print(arr.dtype)

# Output
# (5,)
# 1
# 5
# int64

Numpy Array Indexing and Slicing:

We can access the elements of a numpy array using indexing and slicing.

arr = np.array([1, 2, 3, 4, 5])
print(arr[0])
print(arr[-1])
print(arr[1:3])

# Output
# 1
# 5
# [2 3]

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

# Output
# 2
# [2 5]
# [4 5]

Filter in Python

Reduce in Python

Sets in Python