Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

NumPy Array Creation and Fundamental Operations Guide

Tech 1

Sequences like lists, tuples, or nested structures can be converted into NumPy arrays using the asarray function. This utility ensures data consistency without unnecessary copying when possible.

import numpy as np

data = [1, 2, 3]
result_array = np.asarray(data, dtype=np.int32, order='C')

The parameters include:

  • a: Any array-like object (list, tuple, etc.).
  • dtype: Desired output type; defaults to input type if unspecified.
  • order: Memory layout ('C' for row-major, 'F' for column-major).

Generating Numeric Ranges

Step-Based Sequences

The arange function creates a sequence with a fixed step size between values. The stop value is excluded from the output.

# Start at 0, end before 10
range_seq = np.arange(0, 10)
print(range_seq)

# Start at 1, end before 10, step by 2
step_sequence = np.arange(start=1, stop=10, step=2)
print(step_sequence)

Equally Spaced Intervals

linspace generates a specific number of evenly spaced samples within a defined interval. By default, the interval is closed [start, stop]. Setting endpoint=False makes it half-open [start, stop).

evenly_spaced = np.linspace(start=1, stop=10, num=20)
open_interval = np.linspace(start=0, stop=10, num=5, endpoint=False)

Pre-filled Arrays

Initialize arrays with zeros or ones using dedicated functions. These are efficient for memory allocation.

zeros_matrix = np.zeros((3, 4))
one_matrix = np.ones((3, 4))

Alternatively, create copies with the same shape as an existing array using _like variants:

copy_matrix = np.ones_like(zeros_matrix)

Inspecting Array Attributes

Key metadata properties provide insight into array structure and storage.

Attribute Return Type Description
ndim int Number of dimensions
shape tuple Dimension sizes (e.g., rows, cols)
size int Total count of elements
dtype dtype object Data type of elements
itemsize int Bytes per element
test_arr = np.array([[1, 2], [3, 4]])
print(test_arr.ndim)    # 2
print(test_arr.shape)   # (2, 2)
print(test_arr.size)    # 4
print(test_arr.dtype)   # int64
print(test_arr.itemsize)# 8

Data Types Reference

NumPy supports various primitive types including booleans, signed/unsigned integers, floats, and complex numbers. Common types include:

  • Integers: int8, int16, int32, int64, uint8.
  • Floats: float16, float32, float64.
  • Complex: complex64, complex128.

Explicit types can be set during creation:

int_array = np.array([10, 20], dtype=np.int16)
float_type_check = np.array([1.5]).dtype

Reshaping and Concatenation

Arrays can be modified in size without creating new underlying data buffers where possible.

Reshape vs Resize

reshape changes dimensions but preserves total element count. resize creates a new array, repeating content if the target size exceeds the source.

original = np.array([[1, 2, 3], [4, 5, 6]])
reshaped = original.reshape(3, 2)
resized = np.resize(original, (3, 3))

Appending Values

The append function adds elements to an array. Specifying the axis determines whether items are added along rows or columns. Without an axis, data is flattened.

base_data = np.array([[1, 2, 3], [4, 5, 6]])
# Flatten and add
flat_add = np.append(base_data, [7, 8, 9])
# Add along rows (axis 0)
row_add = np.append(base_data, [[7, 8, 9]], axis=0)
# Add along columns (axis 1)
col_add = np.append(base_data, [[1, 1, 1], [2, 2, 2]], axis=1)

Mathematical and Statistical Operations

NumPy performs operations element-wise across the entire array, eliminating the need for explicit Python loops.

Trigonometric Functions

Compute sine, cosine, or tangent for every element instantly.

angles = np.array([0, np.pi / 4, np.pi / 2])
sin_values = np.sin(angles)

Exponential and Logarithmic

Natural exponentials (exp) and logarithms (log, log10) work similarly.

exp_vals = np.exp(2)
log_val = np.log(10)
sqrt_val = np.sqrt(16)
abs_val = np.abs(-5)

Aggregations

Summarize array data using statistical functions.

data = np.array([10, 20, 30, 40])
total = np.sum(data)
average = np.mean(data)
max_v = np.max(data)
min_v = np.min(data)

Linear Algebra

Perform matrix multiplication, transposition, inversion, and determinant calculations.

matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])

# Dot product
product = np.dot(matrix_a, matrix_b)

# Transpose
transposed = np.transpose(matrix_a)

# Inverse and Determinant
inv_mat = np.linalg.inv(matrix_a)
det_value = np.linalg.det(matrix_a)

Logical Operations

Combine boolean conditions or evaluate truthiness across arrays.

bool_a = np.array([True, False, True])
bool_b = np.array([False, False, True])

and_result = np.logical_and(bool_a, bool_b)
or_result = np.logical_or(bool_a, bool_b)
not_result = np.logical_not(bool_a)

all_true = np.all(bool_b)  # Checks if all are True
any_true = np.any(bool_a)  # Checks if any are True
Tags: PythonNumPy

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.