You can use .replace(), as follows:

df = df.replace({np.inf: df[np.isfinite(df)].max().max(), 
                -np.inf: df[np.isfinite(df)].min().min()})

Here, df[np.isfinite(df)].max().max() and df[np.isfinite(df)].min().min() are the respective finite maximum and minimum of the dataframe. We replace np.inf and -np.inf with them respectively.

Demo

Data Input

df = pd.DataFrame({'Col1': [np.inf, -2000.0, 345.0], 'Col2': [1234.0, -np.inf, 890.0]})


     Col1    Col2
0     inf  1234.0
1 -2000.0    -inf
2   345.0   890.0

Output:

print(df)

     Col1    Col2
0  1234.0  1234.0
1 -2000.0 -2000.0
2   345.0   890.0

Edit

If you want to replace with min max of the particular column instead of the min max over the global dataframe, you can use nested dict in .replace(), as follows:

col_min_max = {np.inf: df[np.isfinite(df)].max(),    # column-wise max
              -np.inf: df[np.isfinite(df)].min()}    # column-wise min

df = df.replace({col: col_min_max for col in df.columns})

Demo

Data Input

df = pd.DataFrame({'Col1': [np.inf, -2000.0, 345.0], 'Col2': [1234.0, -np.inf, 890.0]})


     Col1    Col2
0     inf  1234.0
1 -2000.0    -inf
2   345.0   890.0

Output:

print(df)

     Col1    Col2
0   345.0  1234.0
1 -2000.0   890.0
2   345.0   890.0

inf and -inf are replaced by the respective max, min of the column accordingly.

Answer from SeaBean on Stack Overflow
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to replace infinity with large finite numbers and fill nan values in python
5 Best Ways to Replace Infinity with Large Finite Numbers and Fill NaN Values in Python - Be on the Right Side of Change
March 1, 2024 - This example starts by obtaining the maximum finite float number representable by NumPy to replace ‘inf’ values. Using a boolean mask with np.isinf, the ‘infinity’ values in the array are replaced.
Discussions

python - Replacing np.inf and -np.inf values with maximum and minimum of a column in pandas dataframe? - Stack Overflow
I have some -np.inf and np.inf values in my dataframe. I would like to replace them with the respective minimum and maximum values of the dataframe. I thought it should be possible with something l... More on stackoverflow.com
🌐 stackoverflow.com
python - how to replace infinite value with maximum value of a pandas column? - Stack Overflow
I have a dataframe which looks like City Crime_Rate A 10 B 20 C inf D 15 I want to replace the inf with the max value of the Crime_Rate column , so that my resulting More on stackoverflow.com
🌐 stackoverflow.com
python - find infinity values and replace with maximum per vector in a numpy array - Stack Overflow
Now I want to find the infinity values per vector and replace them with the maximum of that vector, with a lower limit of 1. More on stackoverflow.com
🌐 stackoverflow.com
June 22, 2021
python - Replace -infinty value and infinity value to max and min of the data frame - Stack Overflow
I have a dataframe where I have infinte and -infinite value, I would like to replace it with max and min value of the data frame, I am able to replace for infinte value to max but not able to do the same for -infite value · Copyimport pandas as pd import numpy as np a = float('Inf') b = ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Statology
statology.org › home › pandas: how to replace inf with max value
Pandas: How to Replace inf with Max Value
July 11, 2022 - #find max value of entire data frame max_value = np.nanmax(df[df != np.inf]) #replace all inf and -inf with max value df.replace([np.inf, -np.inf], max_value, inplace=True) #view updated DataFrame print(df) points assists rebounds 0 18.0 5.0 28.0 1 28.0 7.0 8.0 2 19.0 7.0 10.0 3 28.0 9.0 6.0 4 14.0 12.0 6.0 5 11.0 9.0 28.0 6 20.0 9.0 9.0 7 28.0 28.0 12.0 · Notice that each inf and -inf value in every column has been replaced with the max value in the entire data frame of 28.
🌐
Codepointtech
codepointtech.com › home › mastering nan & inf: replace missing & infinite values in numpy
Mastering NaN & Inf: Replace Missing & Infinite Values in NumPy - codepointtech.com
July 4, 2026 - For Inf values, replacing with a very large/small number (like np.finfo().max/min) or the boundary values of your domain can be appropriate.
Top answer
1 of 3
3

You can use .replace(), as follows:

df = df.replace({np.inf: df[np.isfinite(df)].max().max(), 
                -np.inf: df[np.isfinite(df)].min().min()})

Here, df[np.isfinite(df)].max().max() and df[np.isfinite(df)].min().min() are the respective finite maximum and minimum of the dataframe. We replace np.inf and -np.inf with them respectively.

Demo

Data Input

df = pd.DataFrame({'Col1': [np.inf, -2000.0, 345.0], 'Col2': [1234.0, -np.inf, 890.0]})


     Col1    Col2
0     inf  1234.0
1 -2000.0    -inf
2   345.0   890.0

Output:

print(df)

     Col1    Col2
0  1234.0  1234.0
1 -2000.0 -2000.0
2   345.0   890.0

Edit

If you want to replace with min max of the particular column instead of the min max over the global dataframe, you can use nested dict in .replace(), as follows:

col_min_max = {np.inf: df[np.isfinite(df)].max(),    # column-wise max
              -np.inf: df[np.isfinite(df)].min()}    # column-wise min

df = df.replace({col: col_min_max for col in df.columns})

Demo

Data Input

df = pd.DataFrame({'Col1': [np.inf, -2000.0, 345.0], 'Col2': [1234.0, -np.inf, 890.0]})


     Col1    Col2
0     inf  1234.0
1 -2000.0    -inf
2   345.0   890.0

Output:

print(df)

     Col1    Col2
0   345.0  1234.0
1 -2000.0   890.0
2   345.0   890.0

inf and -inf are replaced by the respective max, min of the column accordingly.

2 of 3
1

You can use df.mask() which takes boolean series or dataframes, which you can then get with np.isinf for example.

>>> df
     0
0  0.0
1  1.0
2  inf
3  2.0
4 -inf
5  3.0
>>> posinf = df.gt(0) & df.transform(np.isinf)
>>> neginf = df.lt(0) & df.transform(np.isinf)
>>> df = df.mask(posinf, df.mask(posinf).max().max())
>>> df = df.mask(neginf, df.mask(neginf).min().min())
>>> df
     0
0  0.0
1  1.0
2  3.0
3  2.0
4  0.0
5  3.0

I’m masking twice, the inner call has no replacing value so it replaces with NaN. This allows to then compute the min/max bounds.

🌐
Arab Psychology
scales.arabpsychology.com › psychological scales › how to easily replace infinity with maximum value in a pandas dataframe
How To Easily Replace Infinity With Maximum Value In A Pandas DataFrame
November 28, 2025 - Successfully mitigating the presence of infinite values is a critical checkpoint in preparing data for robust statistical modeling and analysis. The methods detailed above, leveraging the synergy between the Pandas replace() function and NumPy’s capabilities for precise maximum calculation (specifically utilizing np.nanmax() in conjunction with boolean masking), provide reliable pathways for imputing these numerical anomalies.
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.nan_to_num.html
numpy.nan_to_num — NumPy v2.6.dev0 Manual
If no values are passed then positive infinity values will be replaced with a very large number.
Find elsewhere
🌐
Arab Psychology
scales.arabpsychology.com › home › how can i replace infinite values with the maximum value in a pandas dataframe?
How Can I Replace Infinite Values With The Maximum Value In A Pandas Dataframe?
June 27, 2024 - #find max value of entire data frame max_value = np.nanmax(df[df != np.inf]) #replace all inf and -inf with max value df.replace([np.inf, -np.inf], max_value, inplace=True) #view updated DataFrame print(df) points assists rebounds 0 18.0 5.0 28.0 1 28.0 7.0 8.0 2 19.0 7.0 10.0 3 28.0 9.0 6.0 4 14.0 12.0 6.0 5 11.0 9.0 28.0 6 20.0 9.0 9.0 7 28.0 28.0 12.0 · Notice that each inf and -inf value in every column has been replaced with the max value in the entire data frame of 28.
🌐
Stack Overflow
stackoverflow.com › questions › 64570905 › replace-inf-values-of-a-column-with-the-max-value-of-the-column-group-by
python - replace inf values of a column with the max value of the column group by - Stack Overflow
October 28, 2020 - replace · inf · Share · Improve this question · Follow · edited Oct 28, 2020 at 10:39 · yatu · 88.8k1212 gold badges9494 silver badges149149 bronze badges · asked Oct 28, 2020 at 10:26 · suma · 4933 bronze badges 0 · Add a comment | Sorted by: Reset to default · Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 0 · import numpy as np # skip inf records max_df = df[df['sales'] != np.inf] # group by ID without inf for sales_id, id_df in max_df.groupby('ID'): # search in original df by ID + inf and set sales to max value of subgroup df.loc[(df['sales'] == np.inf) & (df['ID'] == sales_id), 'sales'] = id_df['sales'].max() print(df) # ID sales # 0 c1 100.0 # 1 c1 25.0 # 2 c1 60.0 # 3 c1 100.0 # 4 c2 40.0 # 5 c2 40.0 # 6 c3 50.0 # 7 c3 80.0 # 8 c3 80.0 ·
🌐
bioinfo core
bioinfocore.com › home › python › python numpy replace nan in array to 0 or a number
numpy array replace nan inf to 0 or number | bioinfo core
October 21, 2021 - a = numpy.array([1,2,3,4,np.inf]) # change to the most positive or finite floating-point value by default a = numpy.nan_to_num(a, copy=True) # if you want it changed to any number, eg.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.nan_to_num.html
numpy.nan_to_num — NumPy v2.5 Manual
If no values are passed then positive infinity values will be replaced with a very large number.
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.nan_to_num.html
numpy.nan_to_num — NumPy v2.1 Manual
If no value is passed then positive infinity values will be replaced with a very large number.
🌐
GeeksforGeeks
geeksforgeeks.org › python › replace-infinity-with-large-finite-numbers-and-fill-nan-for-complex-input-values-using-numpy-in-python
Replace infinity with large finite numbers and fill NaN for complex input values using NumPy in Python - GeeksforGeeks
May 3, 2022 - In this example, an array is created using numpy.array() method which consists of np.nan and positive infinity. The shape, datatype, and dimensions of the array can be found by .shape, .dtype, and .ndim attributes. Here, np.nan is replaced with 1000 using the nan parameter, and n infinity is replaced with a large finite number.
🌐
AskPython
askpython.com › python-modules › numpy › replacing-nan-infinity-python
Usage of nan_to_num in replacing NaN and Infinity - AskPython
February 23, 2023 - We might come across some datasets with records or values that may not be represented or are usually undefined. Such values are termed as Not a Number, also known as NaN. The presence of such values can cause errors in calculations in a data analysis project. The function nan_to_num can eradicate these values making your project error-free. This function is available in the NumPy library and can also be used for replacing infinity with some number which we are going to see in the coming examples.
🌐
GeeksforGeeks
geeksforgeeks.org › numpy-nan_to_num-in-python
numpy.nan_to_num() in Python - GeeksforGeeks
November 28, 2018 - If arr is inexact, then NaN is replaced by zero, and infinity (-infinity) is replaced by the largest (smallest or most negative) floating point value that fits in the output dtype.