0% found this document useful (0 votes)
2 views4 pages

Numpy Comprehensive Cheatsheet

The document is a comprehensive cheatsheet for NumPy, detailing its core architecture, array types, creation methods, and performance advantages over standard Python lists. It covers essential functionalities such as array inspection, vectorization, broadcasting, mathematical operations, and data processing techniques. Additionally, it provides insights on handling missing values and demonstrates practical applications in data cleaning workflows.

Uploaded by

mayurpmore25
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Numpy Comprehensive Cheatsheet

The document is a comprehensive cheatsheet for NumPy, detailing its core architecture, array types, creation methods, and performance advantages over standard Python lists. It covers essential functionalities such as array inspection, vectorization, broadcasting, mathematical operations, and data processing techniques. Additionally, it provides insights on handling missing values and demonstrates practical applications in data cleaning workflows.

Uploaded by

mayurpmore25
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NumPy for Data Science & AI Cheatsheet

Comprehensive Reference Guide • Concepts from the Full Course Tutorial by Sagar Chouksey

1. Introduction to NumPy & Core Architecture


NumPy (Numerical Python) is the foundational ecosystem powering AI, Machine Learning, Data Science, and Computer
Vision. Created by Travis Oliphant in 2005, it provides an optimized, memory-efficient alternative to standard Python lists
using fixed-size contiguous arrays (ndarray).

Why NumPy instead of Python Lists?


• Speed Performance: Executes operations 50x to 100x faster than traditional Python loops by running optimized
internal C routines.
• Memory Layout: Standard Python lists store distinct references to arbitrary pointer locations. NumPy binds data
inside raw contiguous computational buffers, reducing overhead.

# Core Installation and Standard Import Convention


# Terminal: pip install numpy
import numpy as np

2. Array Types & Dimensions


• 1D Arrays (Vectors): Structured single-sequence entries (like an Excel row or a data series).
• 2D Arrays (Matrices): Standard row/column layout structures (tables, frames, grids).
• 3D / Multi-Dimensional Arrays: Stacked grids used for complex tensors, color image channels (RGB), and spatial
volumetric layouts.

3. Array Creation Methods

Creation Routine Functional Use Case and Target Syntax

From Native Lists arr = [Link]([1, 2, 3])


Converts a native Python list structure directly into an optimized ndarray block.

Zero Arrays [Link](shape=(3, 3))


Initializes arrays filled with floating-point zeros. Useful for pre-allocating memory buffers.

One Arrays [Link](shape=(2, 3))


Populates targeted dimensions filled entirely with 1.0 elements.

Static Constant Fills [Link](shape=(2, 2), fill_value=7)


Instantly generates structures pre-filled with an arbitrary target scalar constant.

Sequence Generation [Link](start=1, stop=10, step=2)


An array-based equivalent to Python's native range(), returning structural elements up
to the stop index (exclusive).

Identity Matrix [Link](4)


Generates a square matrix containing 1.0 along the main diagonal and 0.0 everywhere
else.

NumPy Data Science Reference Cheatsheet • Coding With Sagar Page 1 of 4


4. Array Inspection & Type Transformation
NumPy arrays expose properties that allow inspection of their data types and structural characteristics:

• [Link]: Returns a tuple indicating the length along each major dimension (e.g., (rows, columns)).
• [Link]: Returns the absolute total count of scalar elements packed across all dimensions.
• [Link]: Returns an integer value specifying the absolute number of structural axes (dimensions).
• [Link]: Inspects the underlying layout architecture of the elements (e.g., int64, float64).

# Explicit Structural Layout Data Conversion via .astype()


# Converts floating point arrays safely into integer blocks
int_array = float_array.astype(np.int64)

5. Vectorization & BroadCasting Operations

A. Vectorization (Eliminating Python Loops)


Vectorization applies arithmetic operations directly to entire arrays at once, removing the overhead of slower native Python
loops.

arr = [Link]([10, 20, 30])


res = arr * 3 # Instantly scales every scalar member -> [30, 60, 90]

B. Broadcasting (Handling Varying Dimensional Shapes)


Broadcasting allows arithmetic operations between arrays of different shapes by stretching or copying smaller dimensions to
match larger ones according to strict compatibility checks:

1. Rule 1: If the arrays are identical in shape, element-wise transformations match perfectly.
2. Rule 2: If one array has a length of 1 along an axis, it is stretched along that axis to match the larger array.
3. Rule 3: If dimensions are entirely unequal and neither is 1, the runtime triggers a structural ValueError.

6. Math & Statistical Aggregations


Highly optimized statistical summaries can be performed globally across an entire array or isolated along a specific structural
axis (axis=0 for columns, axis=1 for rows):

• [Link](arr): Accumulates a total sum across all elements.


• [Link](arr): Computes the arithmetic balance average.
• [Link](arr) / [Link](arr): Finds the minimum and maximum boundaries.
• [Link](arr) / [Link](arr): Measures variance and distribution dispersion via Standard Deviation.

7. Indexing, Slicing, & Conditional Filters

A. Standard Slicing (1D and 2D layouts)


Uses the standard [start:stop:step] syntax format. Slicing returns a reference view of the data, meaning edits to the
slice modify the original array.

NumPy Data Science Reference Cheatsheet • Coding With Sagar Page 2 of 4


# 1D Array Reverse Sequence Extraction Trick
reversed_arr = arr[::-1]

# 2D Matrix Slicing Syntax: [row_start:row_stop, col_start:col_stop]


sub_matrix = matrix[0:2, 1:3]

B. Fancy Indexing & Boolean Filter Masking


• Fancy Indexing: Extracts arbitrary index patterns by passing an explicit list of target locations. Unlike slicing, fancy
indexing returns a detached copy of the data.
• Boolean Mask Filters: Filters an array using element-wise logical conditions, matching only items that evaluate to True.

# Fancy Indexing Extraction


selective_items = arr[[0, 2, 4]]

# Boolean Mask Application (Extracts all elements > 25)


filtered_results = arr[arr > 25]

8. Structural Reshaping, Stacking & Splitting


• [Link](rows, cols): Changes array dimensions without changing the underlying data. Elements must match
the original size count exactly.
• Flattening Functions:
◦ [Link](): Returns a flattened 1D reference view (modifying the view affects the parent object).
◦ [Link](): Returns a flattened 1D copy of the array, completely detached from the original object.

• Stacking (Merging):
◦ [Link]((a, b)): Stacks arrays vertically along the row axis (axis=0).
◦ [Link]((a, b)): Stacks arrays horizontally along the column axis (axis=1).

• [Link](arr, sections): Divides an array into equal subsections. Triggers an error if dimensions cannot be split
evenly.

9. Handling Missing & Infinite Values


Real-world pipelines often introduce missing entries (NaN) or illegal numerical results like division by zero (inf).

• [Link](arr): Identifies NaN locations and returns a matching boolean array map.
• [Link](arr): Identifies positive or negative infinity parameters.
• np.nan_to_num(arr, nan=0.0, posinf=1000.0): Replaces illegal missing states or infinite values with safe,
standard replacement values.

10. Real-World Data Processing Project Pattern


The course wraps up by demonstrating a comprehensive workflow to clean a messy dataset (handling nulls, removing
duplicate records, correcting negative values, and filtering anomalies) using both NumPy and Pandas:

NumPy Data Science Reference Cheatsheet • Coding With Sagar Page 3 of 4


# Vectorized replacement logic using NumPy conditions
df['salary'] = [Link](df['salary'] < 0, df['salary'].mean(), df['salary'])

# Outlier filtering logic using standard deviation thresholds


mean_val, std_val = df['salary'].mean(), df['salary'].std()
upper_bound, lower_bound = mean_val + (3 * std_val), mean_val - (3 * std_val)
df_clean = df[(df['salary'] >= lower_bound) & (df['salary'] <= upper_bound)]

NumPy Data Science Reference Cheatsheet • Coding With Sagar Page 4 of 4

You might also like