Python 选择数据帧中最接近零的行中的值
我们有一个包含两列的pandasPython 选择数据帧中最接近零的行中的值,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
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()