我的数据框中有一些 -np.inf
和 np.inf
值。
我想用数据帧各自的最小值和最大值替换它们。
我认为这样的事情应该是可能的:
df.replace([np.inf, -np.inf], [df.max, df.min], axis=1, inplace = True)
但是没有成功。我有这个想法是因为我可以使用类似的东西用 fillna()
替换 nans。
什么是有效的方法?
有numpy版本吗?
感谢您的任何提示!
最佳答案
您可以使用.replace()
,如下:
df = df.replace({np.inf: df[np.isfinite(df)].max().max(),
-np.inf: df[np.isfinite(df)].min().min()})
这里,df[np.isfinite(df)].max().max()
和 df[np.isfinite(df)].min().min()
是数据帧各自的有限最大值和最小值。我们分别用它们替换np.inf
和-np.inf
。
演示
数据输入
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
输出:
print(df)
Col1 Col2
0 1234.0 1234.0
1 -2000.0 -2000.0
2 345.0 890.0
编辑
如果您想替换为特定列的最小最大而不是全局数据帧上的最小最大,您可以在 .replace()
中使用嵌套字典,如下:
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})
演示
数据输入
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
输出:
print(df)
Col1 Col2
0 345.0 1234.0
1 -2000.0 890.0
2 345.0 890.0
inf
和 -inf
相应地替换为相应列的最大值、最小值。
关于python - 用 pandas 数据框中列的最大值和最小值替换 np.inf 和 -np.inf 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69299905/