What is numpy.fmax() in Python?

Python’s numpy.fmax() computes the element-wise maximum of an array. It compares two arrays and returns a new array containing the maximum values.

The difference between the fmax() and maximum() functions in numpy is that the fmax() function ignores NaN values whereas the maximum() function propagates NaN values.

Syntax

numpy.fmax() is declared as follows:

numpy.fmax(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'fmax'>

In the syntax given above, x1 and x2 are non-optional parameters, and the rest are optional parameters.

A universal function (ufunc) is a function that operates on ndarrays in an element-by-element fashion. The fmax() method is a universal function.

Parameters

The numpy.fmax() method takes the following compulsory parameters:

  • x1 and x2 [array-like] - arrays holding the values that need to be compared. If the shapethe shape of an array is the number of elements in each dimension of x1 and x2 is different, they must be broadcastable to a common shape for representing the output.

The numpy.fmax() method takes the following optional parameters:

Parameter

Description

out

represents the location into which the output of the method is stored

where

True value indicates that a universal function should be calculated at this position

casting

controls the type of datacasting that should occur. The same_kind option indicates that safe casting or casting within the same kind should take place. 

order

controls the memory layout order of the output function. The option K means reading the elements in the order they occur in memory

dtype

represents the desired data type of the array

subok

decides if subclasses should be made or not. If True, subclasses will be passed through. 

Return value

numpy.fmax() returns the maximum of x1 and x2 element-wise. The return type is ndarray or scalar, depending on the input. Only if both x1 and x2 are scalar will the value returned be scalar.

If one of the elements being compared is NaN (Not a Number), then the non-nan element is returned.

If both elements being compared are NaN (Not a Number), then NaN is returned.

Examples

The examples below show different ways in which numpy.fmax() is used in Python.

The following code example outputs the maximum of two numbers a and b:

import numpy as np
a = 10
b = np.nan
print(np.fmax(a,b))

The example below outputs the result after comparing the arrays arr1 and arr2:

import numpy as np
arr1 = np.array([1.5,3.5,4,np.nan])
arr2 = np.array([np.nan,6.5,2,np.nan])
print(np.fmax(arr1,arr2))

The example below shows the result of comparing the arrays arr3 and arr4:

import numpy as np
arr3 = np.array([[1,2,3], [4,5,6]])
arr4 = np.array([[3,np.nan,1], [6,-5,4]])
print(np.fmax(arr3,arr4))

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved