在 Pandas.DataFrame 中,我想找到给定列中的值最接近(但低于)指定值的行的索引。具体来说,假设我得到了数字 40 和 DataFrame df:
| | x |
|---:|----:|
| 0 | 11 |
| 1 | 15 |
| 2 | 17 |
| 3 | 25 |
| 4 | 54 |
我想找到 df["x"] 较低但尽可能接近 40 的行索引。这里,答案为 3,因为 df[3,'x']=25 较小比给定数字 40 但最接近它。 我的数据框还有其他列,但我可以假设列“x”正在增加。
为了精确匹配,我做了(如果有更好的方法请纠正我):
list = df[(df.x == number)].index.tolist()
if list:
result = list[0]
但对于一般情况,我不知道如何以“矢量化”方式做到这一点。
最佳答案
按 Series.lt
过滤 40 以下的行在 boolean indexing
并通过 Series.idxmax
得到 mximal 索引值:
a = df.loc[df['x'].lt(40), 'x'].idxmax()
print (a)
3
为了提高性能,可以使用 numpy.where
使用np.max
,如果默认索引,解决方案有效:
a = np.max(np.where(df['x'].lt(40))[0])
print (a)
3
如果不是默认RangeIndex
:
df = pd.DataFrame({'x':[11,15,17,25,54]}, index=list('abcde'))
a = np.max(np.where(df['x'].lt(40))[0])
print (a)
3
print (df.index[a])
d
关于python - Pandas .DataFrame : find the index of the row whose value in a given column is closest to (but below) a specified value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60149936/