Facebook Page Twitter Page LinkedIn Page
× NumPy Tutorial NumPy Resources

The NumPy std() function is used to compute the standard deviation along the specified axis. The standard deviation is defined as the square root of the average of the squared deviations from the mean. Mathematically, it can be represented as:

std = sqrt(mean(abs(x - x.mean())**2))


numpy.std(a, axis=None, dtype=None, out=None, keepdims=<no value>)


a Required. Specify the input array.
axis Optional. Specify axis or axes along which the standard deviation is calculated. The default, axis=None, computes the standard deviation of the flattened array..
dtype Optional. Specify the type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type.
out Optional. Specify the output array in which to place the result. It must have the same shape as the expected output.
keepdims Optional. If this is set to True, the reduced axes are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

Return Value

Returns an array containing the standard deviation if out=None, otherwise return a reference to the output array.

Example: Standard deviation of flattened array

In the below example, std() function is used to calculate standard deviation of all values present in the array.

import numpy as np
Arr = np.array([[1,2],[3, 4]])

print("Array is:")

#standard deviation of all values
print("\nStandard deviation of all values:", np.std(Arr))

The output of the above code will be:

Array is:
[[1 2]
 [3 4]]

Standard deviation of all values: 1.118033988749895

Example: std() with axis parameter

When axis parameter is provided, standard deviation is calculated over the specified axes as shown in the below example.

import numpy as np
Arr = np.array([[10,20,30],[70,80,90]])

print("Array is:")

#standard deviation along axis=0
print("\nStandard deviation along axis=0")
print(np.std(Arr, axis=0))

#standard deviation along axis=1
print("\nStandard deviation along axis=1")
print(np.std(Arr, axis=1))

The output of the above code will be:

Array is:
[[10 20 30]
 [70 80 90]]

Standard deviation along axis=0
[30. 30. 30.]

Standard deviation along axis=1
[8.16496581 8.16496581]

Example: std() with dtype parameter

Computing the standard deviation in float64 gives more accurate result. consider the following example.

import numpy as np
Arr = np.array([1, 10, 100, 1000])

#standard deviation using float32
print("Standard deviation using float32:", np.std(Arr, dtype=np.float32))

#standard deviation using float64
print("Standard deviation using float64:", np.std(Arr, dtype=np.float64))

The output of the above code will be:

Standard deviation using float32: 418.78418
Standard deviation using float64: 418.7841777097124

❮ NumPy - Functions