Mastering NumPy Arrays

👋 Hi there, I am Nirmal. I am a former software engineer with a keen interest in data science and analytics domains. Besides, I love to contribute to open source and help others to understand various tech stuffs.
Search for a command to run...

👋 Hi there, I am Nirmal. I am a former software engineer with a keen interest in data science and analytics domains. Besides, I love to contribute to open source and help others to understand various tech stuffs.
No comments yet. Be the first to comment.
This series will provides the core concepts of python programming starting from variables, data types, control flow, and functions to some problem solving.
Python is a high-level general purpose that welcomes both newcomers and experienced developers with its user-friendly approach and simplicity, making it accessible for anyone to learn and utilize effectively. It is massively used in various domains l...
Bias in Machine Learning Bias refers to the simplifying assumptions made by a model to make the target function easier to learn. High bias can lead to underfitting Represents the error introduced by approximating a real-world problem Example: A li...
When it comes to developing software applications, choosing the appropriate architectural style is a critical decision. Among the popular options are microservices and monolithic architecture. By understanding the trade-offs, readers can make well-i...

In a world where information is everywhere, businesses have tons of data at their fingertips. This data is like a goldmine waiting to be used for smart decisions. That's where Big Data analytics and Data Science come in. They're like the experts who ...

Python is a powerful tool for data professionals, largely due to its extensive collection of open-source libraries and packages. In this blog, we'll explore the fundamentals of pandas, with a special focus on its core data structures: Series and Data...

NumPy is a powerful library for numerical computing in Python, offering robust support for large, multi-dimensional arrays and an extensive collection of mathematical functions.
To begin using NumPy, import the library and create arrays:
import numpy as np
# 1D array (Similar to a list.)
array_1d = np.array([1, 2, 3])
print(array_1d) # Output: [1 2 3]
# 2D array(Similar to a table.)
array_2d = np.array([(1, 2, 3), (4, 5, 6)])
print(array_2d) # Output: [[1 2 3] [4 5 6]]
# 3D array(Similar to two tables)
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(array_3d) # Output: [[[1 2] [3 4]] [[5 6] [7 8]]]
Create arrays filled with zeros(), ones(), full().
# Array of zeros
print(np.zeros((3, 2))) # Output: [[0 0] [0 0] [0 0]]
# Array of ones
print(np.ones((2, 2))) # Output: [[1 1] [1 1]]
# Array filled with a specific value
print(np.full((5, 3), 8)) # Output: [[8 8 8] [8 8 8] [8 8 8] [8 8 8] [8 8 8]]
NumPy arrays have several attributes that enable you to access information about the array. Some of the most commonly used attributes include the following:
ndarray.shape: returns a tuple of the array’s dimensions.
ndarray.dtype: returns the data type of the array’s contents.
ndarray.size: returns the total number of elements in the array.
ndarray.T: returns the array transposed rows becomes columns, columns become rows).
array = np.array([(1, 2, 3), (4, 5, 6)])
print(array )# Output: [ [1 2 3] [4 5 6] ]
print(array.shape)# Output: (2, 3)
print(array.dtype)# Output: int64
print(array.size)# Output: 6
print(array.T)# Output:[ [1 4] [2 5] [3 6]]
Some important array methods are flatten() , reshape(), and tolist().
array = np.array([(1, 2, 3), (4, 5, 6)])
# Flatten an array( returns a copy of the array collapsed into one dimension.)
print(array .flatten()) # Output: [1 2 3 4 5 6]
# Reshape an array( Gives a new shape to an array without changing its data.)
print(array .reshape(3, 2)) # Output: [[1 2] [3 4] [5 6]]
# Reshape with inferred dimension
print(array .reshape(3, -1)) # Output: [[1 2] [3 4] [5 6]]
# Convert array to list(Converts an array to a list object.)
print(array .tolist()) # Output: [[1, 2, 3], [4, 5, 6]]
Some common mathematical operations : max(), mean(), min(), std().
array = np.array([(1, 2, 3), (4, 5, 6)])
# Maximum value
print(array .max()) # Output: 6
# Mean value
print(array .mean()) # Output: 3.5
# Minimum value
print(array .min()) # Output: 1
# Standard deviation
print(array .std()) # Output: 1.707825127659933
Access individual elements of a NumPy array using indexing and slicing.
Indexing in NumPy is similar to indexing in Python lists, except multiple indices can be used to access elements in multidimensional arrays.
array = np.array([(1, 2, 3), (4, 5, 6)])
# Indexing
print(array [1]) # Output: [4 5 6]
print(array [0, 1]) # Output: 2
print(array [1, 2]) # Output: 6
# Slicing to access subarrays of a NumPy array
print(array [:, 1:]) # Output: [[2 3] [5 6]]
NumPy arrays support a variety of operations, including mathematical functions and arithmetic, such as element-wise addition and multiplication.
a = np.array([(1, 2, 3), (4, 5, 6)])
b = np.array([[1, 2, 3], [1, 2, 3]])
print(a) # Output: [[1 2 3] [4 5 6]]
print(b) # Output: [[1 2 3] [1 2 3]]
print(a + b) # Output: [[2 4 6] [5 7 9]]
print(a * b) # Output: [[ 1 4 9] [ 4 10 18]]
Furthermore, there are other crucial mathematical functions that can be applied to individual or multiple arrays.
NumPy arrays are mutable, though they have certain limitations. For example, you can modify an existing element in an array:
# Modify an element
a[1][1] = 100
print(a) # Output: [[ 1 2 3] [ 4 100 6]]
# Attempt to add an element (will cause an error)
a[3] = 100 # Uncommenting this will raise an IndexError
To conclude, NumPy arrays allocate a contiguous block of memory, ensuring fast access and manipulation but restricting the ability to resize after creation.
By mastering these core functionalities, you can leverage NumPy arrays for efficient numerical computing and data manipulation in your projects. Save this guide for quick reference and further practice as you delve deeper into data science and numerical analysis with NumPy.