Array Creation and Logic Functions

This final NumPy topic covers a few remaining array creation shortcuts, along with logic functions that let you compare and filter array data using boolean conditions.

More Array Creation Shortcuts

import numpy as np

print(np.eye(3))          # 3x3 identity matrix
print(np.full((2, 2), 7)) # 2x2 array filled entirely with the value 7
print(np.empty(3))        # uninitialized array (values are whatever was in memory)

Logical and Comparison Functions

import numpy as np

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

print(a > 3)                     # [False False False  True  True]
print(np.any(a > 3))             # True - at least one element satisfies condition
print(np.all(a > 0))             # True - every element satisfies condition
print(np.logical_and(a > 1, a < 5))   # [False  True  True  True False]

Boolean Indexing (Filtering with Conditions)

Boolean indexing is one of NumPy's most powerful features - it lets you filter an array using a condition, returning only the elements that satisfy it, without needing a manual loop.

import numpy as np

scores = np.array([45, 78, 92, 34, 88, 61])

passing = scores[scores >= 50]
print(passing)   # [78 92 88 61]

scores[scores < 50] = 0   # replace failing scores with 0
print(scores)
Boolean indexing is used constantly in real data analysis - it's the same underlying technique Pandas uses when you filter a DataFrame with a condition, so mastering it here makes filtering data in Pandas feel immediately familiar.

Coming Up Next

With NumPy covered end to end, the course now introduces Pandas - the library you'll use most for real-world, tabular data analysis.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course