Guide for using NumPy, the fundamental package for scientific computing and array operations in Python. Learn to perform efficient numerical computations, linear algebra, and data manipulation.
A comprehensive guide for using NumPy, the fundamental package for scientific computing with Python. NumPy provides powerful N-dimensional array objects, broadcasting functions, and tools for numerical operations.
This skill helps you effectively use NumPy for:
NumPy can be installed via pip or conda:
```bash
pip install numpy
conda install -c conda-forge numpy
```
Always start by importing NumPy with the standard alias:
```python
import numpy as np
```
Create NumPy arrays from Python lists or using built-in functions:
```python
arr = np.array([1, 2, 3, 4, 5])
zeros = np.zeros((3, 4)) # 3x4 array of zeros
ones = np.ones((2, 3)) # 2x3 array of ones
arange = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
linspace = np.linspace(0, 1, 5) # 5 evenly spaced values from 0 to 1
random_arr = np.random.rand(3, 3) # 3x3 array of random values
```
Leverage NumPy's vectorized operations for efficiency:
```python
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
sum_arr = a + b # [5, 7, 9]
product = a * b # [4, 10, 18]
matrix = np.array([[1, 2, 3], [4, 5, 6]])
scaled = matrix * 2 # Multiply all elements by 2
total = np.sum(a)
mean = np.mean(a)
std_dev = np.std(a)
```
Access and manipulate array elements:
```python
arr = np.array([10, 20, 30, 40, 50])
first = arr[0] # 10
last = arr[-1] # 50
subset = arr[1:4] # [20, 30, 40]
mask = arr > 25
filtered = arr[mask] # [30, 40, 50]
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
element = matrix[1, 2] # 6
row = matrix[0, :] # [1, 2, 3]
```
Change array dimensions and structure:
```python
arr = np.arange(12)
reshaped = arr.reshape(3, 4) # 3x4 matrix
transposed = reshaped.T
flattened = reshaped.flatten()
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
stacked = np.vstack([a, b]) # Vertical stack
hstacked = np.hstack([a, b]) # Horizontal stack
```
Use NumPy's linear algebra capabilities:
```python
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
product = np.dot(A, B) # or A @ B
det = np.linalg.det(A)
inv = np.linalg.inv(A)
eigenvalues, eigenvectors = np.linalg.eig(A)
b = np.array([1, 2])
x = np.linalg.solve(A, b)
```
Perform statistical analysis:
```python
data = np.random.randn(100)
mean = np.mean(data)
median = np.median(data)
std = np.std(data)
variance = np.var(data)
percentile_25 = np.percentile(data, 25)
percentile_75 = np.percentile(data, 75)
x = np.random.rand(50)
y = x + np.random.randn(50) * 0.1
correlation = np.corrcoef(x, y)
```
Generate random data for simulations and testing:
```python
np.random.seed(42)
integers = np.random.randint(0, 100, size=10)
uniform = np.random.rand(5)
normal = np.random.randn(1000)
choices = np.random.choice(['a', 'b', 'c'], size=10)
```
Work with NaN (Not a Number) values:
```python
arr = np.array([1, 2, np.nan, 4, 5])
has_nan = np.isnan(arr)
cleaned = arr[~np.isnan(arr)]
filled = np.nan_to_num(arr, nan=0)
mean_ignoring_nan = np.nanmean(arr)
sum_ignoring_nan = np.nansum(arr)
```
Follow best practices for efficient NumPy code:
```python
result = []
for i in range(len(arr)):
result.append(arr[i] * 2)
result = arr * 2
arr += 5 # In-place addition
large_array = np.empty((1000, 1000))
int_array = np.array([1, 2, 3], dtype=np.int32) # Smaller memory footprint
```
```python
import numpy as np
data = np.array([10, 20, 30, 40, 50])
normalized = (data - data.min()) / (data.max() - data.min())
print(normalized) # [0. 0.25 0.5 0.75 1.]
```
```python
import numpy as np
image = np.random.randint(0, 256, size=(100, 100), dtype=np.uint8)
blurred = (image[:-2, :-2] + image[1:-1, :-2] + image[2:, :-2] +
image[:-2, 1:-1] + image[1:-1, 1:-1] + image[2:, 1:-1] +
image[:-2, 2:] + image[1:-1, 2:] + image[2:, 2:]) // 9
```
```python
import numpy as np
time = np.arange(0, 10, 0.1)
signal = np.sin(time) + np.random.normal(0, 0.1, len(time))
window_size = 10
moving_avg = np.convolve(signal, np.ones(window_size)/window_size, mode='valid')
```
After installation, verify NumPy is working correctly:
```bash
python -c "import numpy, sys; sys.exit(numpy.test() is False)"
```
This requires `pytest` and `hypothesis` to be installed.
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/numpy-array-computing/raw