我有一个数据框,看起来像
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
值,然后得到Series
max
:
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
以下是整个矩阵/数据帧的解决方案:
highest_non_inf = df.max().loc[lambda v: v<np.Inf].max()
df.replace(np.Inf, highest_non_inf)
将use_inf_as_nan
设置为 true,然后使用 fillna。(如果您想将inf
和nan
都视为缺失值,请使用此选项(,即
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((中使用附加函数替换(np.inf,np.nan(的一种方法。
对于 max(( 内部发生的操作,它将 inf 替换为 nan,max 返回预期的最大值而不是 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
希望有效!
使用 numpy 剪辑。它优雅而快速:
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"])
。