Whether you're diving into data science or building machine learning pipelines, NumPy is your ultimate ally. In this article, we’ll break down three crucial areas that every Python developer must master:
Understanding NumPy Array Attributes
Mastering Indexing, Slicing, and Array Operations
Performing Statistical Analysis on NumPy Arrays
Let’s unlock the power of NumPy step by step 🔍
ndim
, shape
, size
, dtype
, and MoreNumPy arrays, known as ndarray
, come with powerful attributes that let you inspect and manipulate them efficiently. Let’s look at the most useful ones:
ndim
: Number of Dimensionsimport numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.ndim) # Output: 2
💡 This tells you how many axes (dimensions) your array has. In the above example, it's a 2D array.
shape
: Tuple of Array Dimensionsprint(arr.shape) # Output: (2, 3)
💡 The shape
shows 2 rows and 3 columns.
size
: Total Number of Elementsprint(arr.size) # Output: 6
💡 Total elements = rows × columns.
dtype
: Data Type of Array Elementsprint(arr.dtype) # Output: int64
💡 NumPy arrays are homogeneous; all elements have the same type.
itemsize
and nbytes
print(arr.itemsize) # Size in bytes of each element
print(arr.nbytes) # Total bytes consumed by the array
Access elements using standard Python indexing:
print(arr[1, 2]) # Output: 6
You can slice like lists but with a multi-dimensional twist:
print(arr[0, :2]) # Output: [1 2] (first row, first two columns)
print(arr[arr > 3]) # Output: [4 5 6]
a. Element-wise Addition
b = np.array([[1, 1, 1], [1, 1, 1]])
print(arr + b)
Output:
[[2 3 4]
[5 6 7]]
b. Broadcasting
You can add a 1D array to a 2D array:
c = np.array([10, 20, 30])
print(arr + c)
Output:
[[11 22 33]
[14 25 36]]
Let’s now explore how to extract key statistical insights from NumPy arrays.
max()
, min()
, mean()
print(np.max(arr)) # Output: 6
print(np.min(arr)) # Output: 1
print(np.mean(arr)) # Output: 3.5
std()
- Standard Deviationprint(np.std(arr)) # Output: 1.7078
Mean of each column:
print(np.mean(arr, axis=0)) # Output: [2.5 3.5 4.5]
Max of each row:
print(np.max(arr, axis=1)) # Output: [3 6]
Mastering NumPy means mastering performance, productivity, and precision in your Python projects. In this post, we looked at:
Essential array attributes like ndim
, shape
, size
, dtype
Powerful slicing and indexing tools
Element-wise operations and broadcasting
Statistical functions that turn raw data into insights
Now go experiment with your own arrays—play, analyze, and explore! 🚀
Join Jugal on Peerlist!
Join amazing folks like Jugal and thousands of other people in tech.
Create ProfileJoin with Jugal’s personal invite link.
0
8
0