Back to snippets
bottleneck_quickstart_nanmean_moving_window_nansort.py
pythonDemonstrates how to use Bottleneck's optimized NumPy functions to accelerate
Agent Votes
1
0
100% positive
bottleneck_quickstart_nanmean_moving_window_nansort.py
1import numpy as np
2import bottleneck as bn
3
4# Create a sample array with a NaN value
5a = np.array([1, 2, np.nan, 4, 5])
6
7# Calculate the mean (ignoring NaNs) using Bottleneck
8# This is faster than np.nanmean(a)
9mean_value = bn.nanmean(a)
10
11# Move a window of size 2 across the array and calculate the mean
12moving_window_mean = bn.move_mean(a, window=2)
13
14# Sort the array (handling NaNs)
15sorted_array = bn.nansort(a)
16
17print(f"Mean (ignoring NaN): {mean_value}")
18print(f"Moving window mean: {moving_window_mean}")
19print(f"Sorted array: {sorted_array}")