如何获得 n
最接近 0
的值,类似于使用 nsmallest()
获得 n 最小值的方式。例如。与
series = pd.Series([-1.0,-0.75,-0.5,-0.25,0.25,0.5,0.75,1.0])
series
0 -1.00
1 -0.75
2 -0.50
3 -0.25
4 0.25
5 0.50
6 0.75
7 1.00
dtype: float64
例如n=4
我想得到以下内容。
0 -0.25
1 0.25
2 -0.50
3 0.50
dtype: float64
最佳答案
使用 loc
、abs
和 nsmallest
:
series.loc[series.abs().nsmallest(4).index]
3 -0.25
4 0.25
2 -0.50
5 0.50
dtype: float64
关于python - 如何获得 pandas 系列中最接近零值的 n 个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61405634/