Python Data Science Jobs & Interviews
20.3K subscribers
187 photos
4 videos
25 files
325 links
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.

Admin: @Hussein_Sheikho
Download Telegram
🚀 NumPy Tip: Boolean Indexing (Masking) 🚀

Ever need to filter your arrays based on a condition? NumPy's Boolean Indexing, also known as masking, is your go-to! It allows you to select elements that satisfy a specific condition.

import numpy as np

Create a sample NumPy array

data = np.array([12, 5, 20, 8, 35, 15, 30])

Create a boolean mask: True where value is > 10, False otherwise

mask = data > 10
print("Boolean Mask:", mask)

Apply the mask to the array to filter elements

filtered_data = data[mask]
print("Filtered Data (values > 10):", filtered_data)

You can also combine the condition and indexing directly

even_numbers = data[data % 2 == 0]
print("Even Numbers:", even_numbers)

Explanation:
A boolean array (the mask) is created by applying a condition to your original array. When this mask is used for indexing, NumPy returns a new array containing only the elements where the mask was True. Simple, powerful, and efficient!

#NumPy #PythonTips #DataScience #ArrayMasking #Python #Programming

---
By: @DataScienceQ