Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 选择数据帧中最接近零的行中的值_Python_Pandas - Fatal编程技术网

Python 选择数据帧中最接近零的行中的值

Python 选择数据帧中最接近零的行中的值,python,pandas,Python,Pandas,我们有一个包含两列的pandasDataFrame: pd.DataFrame(pd.np.arange(12).reshape(6,2), columns=list('ab')) % 3 - 1.2 a b 0 -1.2 -0.2 1 0.8 -1.2 2 -0.2 0.8 3 -1.2 -0.2 4 0.8 -1.2 5 -0.2 0.8 获得最接近零的值的最佳方法是什么?上述项目的预期产出为 x 0 -0.2 1 0.8 2 -0.2 3 -0

我们有一个包含两列的pandas
DataFrame

pd.DataFrame(pd.np.arange(12).reshape(6,2), columns=list('ab')) % 3 - 1.2

     a    b
0 -1.2 -0.2
1  0.8 -1.2
2 -0.2  0.8
3 -1.2 -0.2
4  0.8 -1.2
5 -0.2  0.8
获得最接近零的值的最佳方法是什么?上述项目的预期产出为

     x
0 -0.2
1  0.8 
2 -0.2  
3 -0.2
4  0.8 
5 -0.2 
我尝试使用
df.idxmin(axis=1)
,然后使用
lookup
,但我打赌有一种更简单的方法?

一个选项:

df = pd.DataFrame(pd.np.arange(12).reshape(6,2), columns=list('ab')) % 3 - 1.2
closest_to_zero = df.abs().idxmin(axis=1).pipe(lambda x: x[x.notnull()])
pd.Series(df.lookup(closest_to_zero.index, closest_to_zero), index=closest_to_zero.index).reindex(df.index)

只需在“a”或“b”中的值之间选择位置

df['a'].where(df['a'].abs() < df['b'].abs(), df['b'])

但它看起来还是比它应该的更麻烦?

以下内容对我有效,给了您最接近于零的值:

   df.abs().min()

这将返回最小值或索引?它返回最小值
   df.abs().min()