所以我有一个包含多列的数据框。对于每一列,我希望获得第一行的索引,该索引几乎等于用户指定的数字(例如,在所需数字的 0.05 范围内)。数据框看起来有点像这样:
ix col1 col2 col3
0 nan 0.2 1.04
1 0.98 nan 1.5
2 1.7 1.03 1.91
3 1.02 1.42 0.97
假设我想要第一行几乎等于 1.0,我希望结果是:
- col1 的索引 1(不是索引 3,尽管它们在数学上同样接近 1.0)
- col2 的索引 2
- col3 的索引 0(不是索引 3,尽管 0.97 比 1.04 更接近 1)
我尝试了一种使用 argsort() 的方法:
df.iloc[(df.col1-1.0).abs().argsort()[:1]]
根据其他主题,这将为我提供 col1 中值最接近 1.0 的行的索引。然而,它只返回一个充满 nan 的数据帧。我还想像此方法不会给出每列遇到的第一个接近 1 的值,而是给出最接近 1 的值。
谁能帮我解决这个问题吗?
最佳答案
使用 DataFrame.sub
对于差值,通过 abs
转换为绝对值,比较 lt
( <
) 并最后通过 DataFrame.idxmax
获取第一个值的索引:
a = df.sub(1).abs().lt(0.05).idxmax()
print (a)
col1 1
col2 2
col3 0
dtype: int64
但对于更通用的解决方案,如果 bool 掩码失败(没有值在容差范围内),则附加由 True
填充的新列。名字为NaN
:
print (df)
col1 col2 col3
ix
0 NaN 0.20 1.07
1 0.98 NaN 1.50
2 1.70 1.03 1.91
3 1.02 1.42 0.87
s = pd.Series([True] * len(df.columns), index=df.columns, name=np.nan)
a = df.sub(1).abs().lt(0.05).append(s).idxmax()
print (a)
col1 1.0
col2 2.0
col3 NaN
dtype: float64
关于python - 查找与 pandas DataFrame 中的值最接近的第一行的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50837829/