python - 如何获得 pandas 系列中最接近零值的 n 个值?

标签 python python-3.x pandas series

如何获得 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

最佳答案

使用 locabsnsmallest:

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/

相关文章:

python-3.x - 我应该使用 tf.add 还是 + 在 Tensorflow 中添加两个张量?

python - Mrjob 无法在 dataproc 上创建集群 : __init__() got an unexpected keyword argument 'channel'

python - 将 QLineEdit() 放入 QTreeWidgetItem()

python - 带有 MultiIndex : check if string is contained in index level 的 Pandas 数据框

python - 根据间隔选择随机行

python - 如何自定义排序 Pandas 多索引?

python - 在 Pandas 数据框中的特定列中查找所有具有空值的行的索引

python - 如果满足条件,如何使参数可选?

python - 使用 StyleFrame 从 pandas 到 Excel : how to disable the wrap text & shrink to fit?

python - 使用python计算CSV文件中的条目