Core NumPy Array Techniques and Data Handling

Generating Arrays

import numpy as np

# Create a filled vector
vec_ones = np.ones(3)

# Create a zeroed vector
vec_zeros = np.zeros(3)

# Fill specific shape with value
filled_matrix = np.full(shape=(3, 2), fill_value=5)

# Generate sequence with step
counter = np.arange(start=0, stop=5, step=2)

# Random integers in range
rand_int_arr = np.random.randint(low=1, high=10, size=3)

# Uniform random numbers (0.0 to 1.0)
uniform_rnd = np.random.random((2, 3))

# Standard normal distribution samples
normal_sample = np.random.randn(5)

# Define array manually
manual_vec = np.array([2, 1, 3])

Inspecting Attributes

# Get dimensions
dims = rand_arr.shape

# Count total elements
total_count = rand_arr.size

# Check data type structure
struct_type = rand_arr.dtype

Saving Data to Disk

# Generate source data
source_data = np.random.randint(1, 10, 10)
sample_array = np.array([1, 23, 4])

# Compressed save format
np.savez("archive.npz", alpha=sample_array, beta=source_data)

# Text format save
np.savetxt("output.txt", sample_array)

# CSV format with custom separator
np.savetxt("data.csv", sample_array, delimiter=',')

Loading Saved Files

# Load compressed archive
loaded_archive = np.load('archive.npz')
print(loaded_archive['alpha'])
print(loaded_archive['beta'])

# Load text file with explicit type
data_matrix = np.loadtxt("data.csv", delimiter=',', dtype=np.int32)
print(data_matrix)

Memory Management: Copying

# Shallow copy creates a reference to the original
base = np.array([1, 2, 3])
ref_copy = base

# Checking memory addresses confirms same object
print(id(base)) # Same ID as ref_copy
print(id(ref_copy)) 

base[2] = 4
print(base, ref_copy) # Both update: [1 2 4]

# Deep copy creates independent data
deep_copy = base.copy()

# Different IDs indicate separate objects
print(id(base))
print(id(deep_copy)) 

base[2] = 5
print(base, deep_copy) # Independent results

Reshaping Dimensions

# Generate random 2D grid
grid = np.random.randint(1, 10, (3, 2))

# Flatten and reshape
data = np.array([1, 2, 3, 4] * 3).reshape([3, 4])

print(data.T)   # Transpose operation
print(data)     # Modified dimension structure

Stacking Arrays

array_a = np.array([1, 2, 3, 4])
array_b = np.array([4, 5, 6, 5])

# Concatenate along axis 0
combined_h = np.concatenate([array_a, array_b], axis=0)

# Horizontal stack alias
combined_stacked = np.hstack([array_a, array_b])

# Vertical stack
combined_vstack = np.vstack([array_a, array_b])

Splittign Arrays

matrix = np.random.randint(1, 10, (6, 5))
print(matrix)

# Split into equal parts vertically
split_parts = np.split(matrix, indices_or_sections=2, axis=0)

# Split at specific indices
indexed_split = np.split(matrix, indices_or_sections=[3, 5], axis=0)

# Horizontal split by columns
col_splits = np.hsplit(matrix, indices_or_sections=[1, 2])

# Vertical split by rows
row_splits = np.vsplit(matrix, indices_or_sections=2)

Mathematical and Logical Functions

input_vals = np.array([4, 16, 25])
double_precision = np.array([-2.4, 2.2, 2.5])

# Square root calculation
squares = np.sqrt(input_vals)

# Squaring values
squared = np.square(input_vals)

# Clip values within range
cutoff = np.clip(squares, 5, 21)

# Absolute values
abs_vals = np.abs(squares)

# Maximum element
largest = np.max(squares)

# Element-wise maximum between arrays
max_compare = np.maximum(squares, double_precision)

# Logical aggregation (all truthy)
check_all = np.all(input_vals > 0)

# Logical aggregation (any truthy)
check_any = np.any(input_vals > 20)

# Rounding
rounded = np.round(double_precision, 1)

# Floor function
floor_val = np.floor(double_precision)

# Ceiling function
ceil_val = np.ceil(double_precision)

# Conditional selection
conditional_mask = np.where(input_vals > 10, input_vals, 0)

Statistical Calculations

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

# Find maximum value
val_max = np.max(values)

# Find minimum value
val_min = np.min(values)

# Arithmetic mean
val_mean = np.mean(values)

# Median value
val_median = np.median(values)

# Sum of all elements
val_sum = np.sum(values)

# Cumulative sum
cum_val = np.cumsum(values.flatten())

# Index of max value
idx_max = np.argmax(values)

# Indices satisfying condition
condition_indices = np.argwhere(values > 2)

Sorting Mechanisms

numbers = np.array([24, 16, 25])

# Sort and return new array
sorted_copy = np.sort(numbers)

# Sort in place (modifies original)
numbers.sort()

# Descending sort logic
descending = abs(np.sort(-numbers))

# Get sorting permutation indices
perm_indices = np.argsort(numbers)

Set Operations

set_a = np.array([1, 2, 3])
set_b = np.array([2, 3, 4])

# Intersection
common = np.intersect1d(set_a, set_b)

# Union
united = np.union1d(set_a, set_b)

# Difference
unique_to_a = np.setdiff1d(set_a, set_b)

Advanced Indexing

# Boolean mask extraction
mask = data[:, 3] == 0
result = scores[mask].max(axis=0)

Practice Implementation

# Matrix definition
raw_mat = np.array([
    [1, 0, 1, 0, 1],
    [0, 0, 0, 1, 1],
    [1, 1, 0, 1, 0]
])

# Convert to matrix object
mat_obj = np.mat(raw_mat)

# Numerator for similarity
numerator = mat_obj * mat_obj.T

# Denominator normalization factor
denominator = np.sqrt(mat_obj.sum(axis=1) * mat_obj.sum(axis=1).T)

# Output result rounded
output = np.around(numerator / denominator, decimals=3)
print(output)

Tags: Numpy python Arrays data-science Mathematics

Posted on Sat, 07 Nov 2026 16:42:47 +0000 by m00nz00mer