python - Pandas .DataFrame : find the index of the row whose value in a given column is closest to (but below) a specified value

标签 python pandas dataframe

在 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/

相关文章:

python - __setattr__ 方法确保类中的对象不可变

python - 调用时更新对象变量

python - Python 中的并行处理问题

python - 使用条件语句替换 pandas DataFrame 中的条目

python - 使用日期时间索引获取静态时间之前的分钟数

python - 重置 pandas 数据框的值

python - 如何捕获 ThreadPoolExecutor() 中线程死亡的情况?

python - 用多列交换或交换 pandas 数据框中的列名

python - 将 Count 连接到 pandas 中的原始 DataFrame

python - 将 CountVectorizer 中的稀疏矩阵添加到数据框中,并提供分类器的免费信息 - 保持稀疏格式