Essential NumPy Functions for Array Operations

Universal Functions (ufuncs)

NumPy's universal functions, commonly referred to as ufuncs, perform element-wise operations on ndarrays. These functions accept one or more input arrays and return one or more output arrays.

Unary ufuncs

Function Description
abs Computes absolute values for integers and floats
sqrt Computes square root of each element (equivalent to arr ** 0.5)
square Computes square of each element (equivalent to arr ** 2)
sign Returns 1 for positive, 0 for zero, -1 for negative values
ceil Returns the smallest integer greater than or equal to each element
floor Returns the largest integer less than or equal to each element
rint Rounds elements to the nearest integer, preserving dtype
modf Returns fractional and integer parts as separate arrays
isnan Returns a boolean array indicating NaN (Not a Number) values

Binary ufuncs

Function Description
add Adds corresponding elements from two arrays
subtract Subtracts elements of the second array from the first
multiply Multiplies array elements to gether
divide, floor_divide Division and floor division operations
power Raises elements from first array to powers from second array
maximum, fmax Element-wise maximum; fmax ignores NaN values
minimum, fmin Element-wise minimum; fmin ignores NaN values
mod Element-wise modulo operation
copysign Copies sign from second array to first array's values
greater, greater_equal Performs element-wise comparison, returning boolean arrays

Practical Examples

import numpy as np

matrix_a = np.random.randint(1, 10, (4, 5))
matrix_b = np.random.randint(-10, -1, (4, 5))
matrix_a
matrix_b

Copying signs from one array to another:

np.copysign(matrix_a, matrix_b)
sample = np.array([1, 2, np.nan, 3])
sample

Checking for NaN values:

np.isnan(sample)

Unary Operations Practice

values = np.array([3.5, 1.7, 2.2, -7.8, np.nan, 4.6, -3.4])
values

Absolute values:

np.abs(values)

Squaring elements:

np.square(values)

Sign detection:

np.sign(values)

Floor values:

np.floor(values)

Rounding to nearest integer:

np.rint(values)

NaN detection:

np.isnan(values)

Binary Operations

data1 = np.random.randint(1, 20, (4, 5))
data2 = np.random.randint(-10, 10, (4, 5))
data2 = np.where(data2 == 0, 1, data2)
data1
data2

Element-wise addition:

np.add(data1, data2)

Element-wise subtraction:

np.subtract(data1, data2)

Element-wise maximum:

np.maximum(data1, data2)

Modulo operation:

np.mod(data1, data2)

Copying signs:

np.copysign(data1, data2)

Comparison operations:

np.greater(data1, data2)

Array Statistical Functions

NumPy provides comprehensive statistical methods for analyzing array data.

Core Statistical Methods

Method Description
mean Arithmetic mean; returns NaN for empty arrays
sum Sum of all elements
max, min Maximum and minimum values
std, var Standard deviation and variance
argmax, argmin Indices of maximum and minimum values
cumsum, cumprod Cumulative sum and product

The axis parameter controls the direction of calculation: axis=0 operates along columns, while axis=1 operates along rows. Without specification, calculations span all dimensions.

Worked Examples

import numpy as np

sample_data = np.random.randint(1, 10, (4, 5))
sample_data

Output:

array([[6, 2, 8, 5, 9],
       [1, 3, 7, 7, 7],
       [3, 8, 7, 3, 7],
       [4, 7, 5, 7, 3]])

Summation Operations

# Total sum of all elements
np.sum(sample_data)

Output: 109

# Column-wise summation
np.sum(sample_data, axis=0)

Output: array([14, 20, 27, 22, 26])

# Row-wise summation
np.sum(sample_data, axis=1)

Output: array([30, 25, 28, 26])

Finding Maximum Indices

# Flattened array maximum index
np.argmax(sample_data)

Output: 4

# Column-wise maximum indices
np.argmax(sample_data, axis=0)

Output: array([0, 2, 0, 1, 0])

# Row-wise maximum indices
np.argmax(sample_data, axis=1)

Output: array([4, 2, 1, 1])

Computing Mean Values

# Overall mean
np.mean(sample_data)

Output: 5.45

# Column means
np.mean(sample_data, axis=0)

Output: array([3.5, 5., 6.75, 5.5, 6.5])

# Row means
np.mean(sample_data, axis=1)

Output: array([6., 5., 5.6, 5.2])

Cumulative Sum

# Cumulative sum of flattened array
np.cumsum(sample_data)

Output: array([6, 8, 16, 21, 30, 31, 34, 41, 48, 55, 58, 66, 73, 76, 83, 87, 94, 99, 106, 109])

# Column-wise cumulative sum
np.cumsum(sample_data, axis=0)

Output:

array([[ 6,  2,  8,  5,  9],
       [ 7,  5, 15, 12, 16],
       [10, 13, 22, 15, 23],
       [14, 20, 27, 22, 26]])
# Row-wise cumulative sum
np.cumsum(sample_data, axis=1)

Output:

array([[ 6,  8, 16, 21, 30],
       [ 1,  4, 11, 18, 25],
       [ 3, 11, 18, 21, 28],
       [ 4, 11, 16, 23, 26]])

Additional Statistical Practice

import numpy as np

test_array = np.random.randint(1, 10, (3, 4))
test_array

Computing arithmetic mean:

test_array.mean()

Column-wise mean (axis=0):

test_array.mean(axis=0)

Row-wise mean (axis=1):

test_array.mean(axis=1)

Total sum:

test_array.sum()

Column sums:

test_array.sum(axis=0)

Row sums:

test_array.sum(axis=1)

Cumulative sum of flattaned array:

test_array.cumsum()

All and Any Functions

import numpy as np

a = np.arange(6).reshape((2, 3))
b = np.arange(6).reshape((2, 3))
c = np.array([[0, 1, 2], [8, 9, 10]])
if (a == b).all():
    print('Arrays are equal')
else:
    print('Arrays differ')
(a == c).all()
if (a == c).any():
    print('Some elements match')
else:
    print('No matching elements')

Array Manipulation Functions

Overview of Manipulation Methods

Method Description
delete Removes sub-arrays along specified axis
insert Inserts values along given axis
append Adds values to end of array
resize Reshapes array in-place (modifies original)
concatenate Joins arrays along existing axis

Key distinction: reshape() returns a new array without modifying the original, while resize() modifies the array in-place.

Deleting Elements

import numpy as np

original = np.random.randint(1, 10, (5, 5))
original

Without axis specification, treats 2D array as flattened:

np.delete(original, 0)

Row deletion (removes row at index 1):

np.delete(original, 1, axis=0)

Column deletion (removes column at index 0):

np.delete(original, 0, axis=1)

Inserting Elements

target = np.random.randint(1, 10, (5, 5))
target

Inserting a new row:

np.insert(target, 0, [100, 200, 300, 400, 500], axis=0)

Inserting a new column:

np.insert(target, 1, [11, 22, 33, 44, 55], axis=1)

Appending Elements

np.append(target, 100)

Concatenating Arrays

a = np.random.randint(1, 10, (4, 3))
b = np.random.randint(1, 10, (4, 3))
a
b

Vertical stacking (default behavior):

np.concatenate([a, b])

Horizontal stacking:

np.concatenate([a, b], axis=1)

Set Operations

NumPy provides fundamental set operations for 1D arrays.

Method Description
unique Returns sorted unique elements
intersect1d Returns sorted common elements
union1d Returns sorted union of elements
in1d Boolean array indicating membership
setdiff1d Elements in first array but not second

Set Operation Examples

import numpy as np

set_a = np.random.randint(1, 3, 10)
set_a

Extracting unique values:

np.unique(set_a)
range1 = np.arange(10)
range2 = np.arange(5, 15)
range1
range2

Finding common elements:

np.intersect1d(range1, range2)

Checking element membership:

np.in1d(range1, range2)

Random Number Generation

The numpy.random module extends Python's built-in random capabilities, generating large samples efficiently.

Random Functions

Function Description
permutation Randomly orders array (or generates random sequence from integer)
shuffle Randomly permutes sequence in-place
randint Generates random integers within specified range

Random Number Examples

import numpy as np

sequence = np.arange(10)
sequence

Permutation with array input shuffles elements:

np.random.permutation(sequence)

Permutation with integer generates random sequence:

np.random.permutation(10)

Shuffle modifies the original array:

np.random.shuffle(sequence)
sequence

Array Sorting

import numpy as np

sortable = np.random.randint(1, 10, (5, 5))
sortable

Default row-wise sorting (modifies original):

sortable.sort()
sortable

Column-wise sorting:

sortable.sort(axis=0)
sortable

Reverse ordering technique:

sortable[:, 1][::-1]

Using argsort for Index-Based Sorting

The argsort() function returns indices that would sort the array, leaving the original unchanged.

data_points = np.random.randint(10, 100, 5)
data_points

Get sorted indices:

data_points.argsort()

Apply sorted indices to get sorted values:

data_points[data_points.argsort()]

Original array remains unchanged:

data_points

File Input/Output Operations

NumPy handles both binary and text file formats for array persistence.

Binary File Operations

Use np.save() and np.load() for single arrays. Files default to .npy extension. For multiple arrays, np.savez() creates an archive accessed like a dictionary.

Saving a single array:

import numpy as np

grid = np.arange(25).reshape((5, 5))
grid
np.save('my_arr1', grid)

Loading an array:

np.load('my_arr1.npy')

Saving multiple arrays:

second_grid = np.arange(25, 50).reshape((5, 5))
second_grid
np.savez('multi_files', a=grid, b=second_grid)

Loading arrays from archive:

np.load('multi_files.npz')['a']
np.load('multi_files.npz')['b']

Text File Operations

For CSV and similar delimited formats, use np.savetxt() and np.loadtxt() or np.genfromtxt().

Saving to CSV format:

np.savetxt('my_arr_data.txt', grid, delimiter=',', fmt='%s')

Loading with genfromtxt (skipping header and footer rows):

np.genfromtxt('my_arr_data.txt', delimiter=',', skip_header=1, skip_footer=1, dtype=np.str)

Loading without dtype specification:

np.genfromtxt('my_arr_data.txt', delimiter=',', skip_header=1, skip_footer=1)

Tags: Numpy python Data Analysis Arrays ufuncs

Posted on Sun, 20 Sep 2026 16:42:37 +0000 by zrocker