NumPy std(): Standard Deviation, Axes and Degrees of Freedom

numpy.std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False) computes the standard deviation along the specified axis. Both the standalone function np.std() and the array method ndarray.std() evaluate identical dispersion parameters.

Standard deviation measures the amount of variation or dispersion of a set of data values. By default, ddof=0 computes the population standard deviation (dividing by N), whereas setting ddof=1 applies Bessel's correction to calculate the sample standard deviation (dividing by N - 1). For conceptual reduction mechanics, review axis reduction.

ParameterDescription
aInput array-like data containing elements to evaluate
axisAxis or tuple of axes along which standard deviation is computed (default None evaluates the entire array)
dtypeType to use in computing the standard deviation and return value
outAlternative output array to hold the result; must match expected reduction shape
ddofDelta Degrees of Freedom; divisor used in calculation is N - ddof (default 0)
keepdimsWhen True, reduced axes are retained with length one for broadcast compatibility

Create the Sample Array 🔝

std computes how far spread out numerical values are from the mean. Use fixed values for repeatable testing or generate synthetic arrays with random.randint().

import numpy as np

def sample_array():
    return np.array([[6, 3, 2], [7, 2, 2], [6, 2, 9]])

a = sample_array()
print(a)
assert a.shape == (3, 3)

Expected output

[[6 3 2]
 [7 2 2]
 [6 2 9]]

Overall, Column and Row Standard Deviations 🔝

With axis=None, std evaluates dispersion across all elements. Setting axis=0 computes column-wise dispersion, and setting axis=1 computes row-wise dispersion.

a = sample_array()
print("Overall std:", a.std())
print("Column std (axis=0):", a.std(axis=0))
print("Row std (axis=1):", a.std(axis=1))
assert round(a.std(), 4) == 2.5386

Expected output

Overall std: 2.5385910352879693
Column std (axis=0): [0.47140452 0.47140452 3.29983165]
Row std (axis=1): [1.69967317 2.3570226  2.86744176]

keepdims Keeps Reduced Axes with Length One 🔝

Using keepdims=True preserves reduced axes as dimensions of size 1, facilitating direct broadcast operations against the source array.

a = sample_array()
kd_true = a.std(axis=1, keepdims=True)
kd_false = a.std(axis=1, keepdims=False)

print("keepdims=True shape:", kd_true.shape)
print("keepdims=False shape:", kd_false.shape)
assert kd_true.shape == (3, 1)
assert kd_false.shape == (3,)

Expected output

keepdims=True shape: (3, 1)
keepdims=False shape: (3,)

ddof: Population vs Sample Standard Deviation 🔝

Setting ddof=0 computes the population standard deviation (divisor N). Setting ddof=1 applies Bessel's correction (divisor N - 1) to estimate sample standard deviation.

samples_list = [12, 13, 15, 11, 9, 12, 13, 10, 11, 12, 13, 7, 8]
arr_s = np.array(samples_list)

print("Population std (ddof=0):", arr_s.std(ddof=0))
print("Sample std (ddof=1):    ", arr_s.std(ddof=1))

assert round(arr_s.std(ddof=0), 4) == 2.1538
assert round(arr_s.std(ddof=1), 4) == 2.2418

Expected output

Population std (ddof=0): 2.153846153846154
Sample std (ddof=1):     2.2417941532712202

Practical Statistics: Dispersion Across Regions 🔝

Calculate sample standard deviation across regional sales metrics:

regional_sales = np.array([
    [2500, 3100, 2900],
    [4200, 3900, 4100],
    [1500, 1800, 1650]
])
store_variability = regional_sales.std(axis=1, ddof=1)
print("Sample std per store:", np.round(store_variability, 2))

Expected output

Sample std per store: [305.51 152.75 150.  ]

Common Standard Deviation Mistakes 🔝

  • Ignoring ddof for small samples: Failing to set ddof=1 when estimating population parameters from sample data leads to biased variance underestimation.
  • Confusing axis reduction dimensions: Forgetting that std() without an axis reduces the entire multi-dimensional array into a single scalar value.

Exercise: Standard Deviation of Cleaned Sensor Readings 🔝

Given raw sensor readings with outlier error codes marked as -999, compute the valid sample standard deviation for each sensor channel:

raw_readings = np.array([
    [20.5, 21.0, -999, 19.5],
    [-999, 15.2, 14.8, 15.0],
    [30.1, 29.8, 30.2, 29.9]
])
# Target: Compute sample std (ddof=1) excluding negative error values per row

Exercise Solution 🔝

valid_mask = raw_readings >= 0
# Filter rows manually or compute using masked arrays
cleaned_stds = array = [np.std(row[row >= 0], ddof=1) for row in raw_readings]
print("Cleaned sensor sample stds:", np.round(cleaned_stds, 4))

Expected output

Cleaned sensor sample stds: [0.755 0.2   0.171 ]

Practice in Google Colab

Test standard deviation calculations, explore degrees of freedom, and run verification test suites in our interactive Google Colab companion notebook:

Interactive Practice: Colab & GitHub

Launch the notebook directly in Google Colab to run live code cells or inspect the source repository on GitHub:

View on GitHub Open In Colab

Continue exploring related functions: mean(), sum(), min(), max(), and axis reduction.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer