如何用 pandas 列的最大值替换无限值?

how to replace infinite value with maximum value of a pandas column?

我有一个看起来像

的数据框
City   Crime_Rate

A      10

B      20 

C      inf

D      15 

我想用 Crime_Rate 列的最大值替换 inf,这样我得到的数据框应该看起来像

City   Crime_Rate

A      10

B      20 

C      20

D      15

我试过了

df['Crime_Rate'].replace([np.inf],max(df['Crime_Rate']),inplace=True)

但是python取inf为最大值,我哪里错了?

先过滤掉inf个值,然后得到maxSeries:

m = df.loc[df['Crime_Rate'] != np.inf, 'Crime_Rate'].max()
df['Crime_Rate'].replace(np.inf,m,inplace=True)

另一个解决方案:

mask = df['Crime_Rate'] != np.inf
df.loc[~mask, 'Crime_Rate'] = df.loc[mask, 'Crime_Rate'].max()

print (df)
  City  Crime_Rate
0    A        10.0
1    B        20.0
2    C        20.0
3    D        15.0

use_inf_as_nan 设置为 true,然后使用 fillna。 (如果您想将 infnan 都视为缺失值,请使用此选项)即

pd.options.mode.use_inf_as_na = True

df['Crime_Rate'].fillna(df['Crime_Rate'].max(),inplace=True)

   City  Crime_Rate
0    A        10.0
1    B        20.0
2    C        20.0
3    D        15.0

一种方法是在 max() 中使用附加函数 replace(np.inf, np.nan)

对于 max() 和 max 内部发生的操作,它用 nan 替换了 inf returns 预期的最大值不是 inf

以下示例:最大值为 100 并替换 inf

#Create dummy data frame
import pandas as pd 
import numpy as np  
a = float('Inf')
v = [1,2,5,a,10,5,a,5,100,2]  
df = pd.DataFrame({'Col_A': v})
#Data frame looks like this
In [33]: df
Out[33]: 
        Col_A
0    1.000000
1    2.000000
2    5.000000
3         inf
4   10.000000
5    5.000000
6         inf
7    5.000000
8  100.000000
9    2.000000

# Replace inf  
df['Col_A'].replace([np.inf],max(df['Col_A'].replace(np.inf, 
np.nan)),inplace=True)

In[35]: df
Out[35]: 
   Col_A
0    1.0
1    2.0
2    5.0
3  100.0
4   10.0
5    5.0
6  100.0
7    5.0
8  100.0
9    2.0

希望有用!

这是整个 matrix/data 框架的解决方案:

highest_non_inf = df.max().loc[lambda v: v<np.Inf].max() df.replace(np.Inf, highest_non_inf)

使用numpy clip。它优雅且速度极快:

import numpy as np
import pandas as pd
df = pd.DataFrame({"x": [-np.inf, +np.inf, np.nan, 4, 3]})
df["x"] = np.clip(df["x"], -np.inf, 100)
# Out:
#       x
# 0   -inf
# 1  100.0
# 2    NaN
# 3    4.0
# 4    3.0

要同时消除负无穷大,请将 -np.inf 替换为较小的数字。 NaN 始终不受影响。要获得最大值,请使用 max(df["x"]).