python - 搜索 pandas 数据框列,其输入值小于下一个索引列值

标签 python pandas

我想搜索数据帧以查找与索引行和列值相对应的值。但是,我很挣扎,因为列标题值是范围的上限,其中前一个列标题值是下限(但其其他相邻列值的上限)。

我找不到将我的输入与范围下限对应的列相匹配的方法。

通过一个例子很容易看出:

data_frame_test = pd.DataFrame({'location' : [1, 2, 'S'],
                                '200' : [342, 690, 103],
                                '1000' : [322, 120, 193],
                                '2000' : [249, 990, 403]})

data_frame_test = data_frame_test.set_index('location')

我想做的是这个

location = 1
weight = 500

output = data_frame_test.iloc[1][??] #must be equal to 342

看,重量必须查看的列是 200,因为它在]200;1000[之间的范围内。我不知道还有什么可以尝试将其转换为 python 代码。任何帮助将不胜感激。

最佳答案

您可以创建一个自定义函数,它将迭代列以检查正确的列,然后返回该位置的单元格:

def get_val(location, weight, df):
    col = df.columns[0]
    for c in df.columns:
        if weight >= int(c):
            col = c
        else:
            break
    return df.loc[location, col]
get_val(1, 500, data_frame_test)

关于python - 搜索 pandas 数据框列,其输入值小于下一个索引列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60299176/

相关文章:

Python TypeError : list indices must be integers or slices, 不是元组

python - Python逗号分隔列表

python - Pandas 中的 Groupby 列并执行计算 (Python)

Python在使用函数替换文本时比较pandas df中的两列

Python Tkinter - 一段时间后隐藏一个小部件

android - 无法显示 HTML 字符串

python - 检测 Pandas Dataframe 中的浮点值

python - 将数据粘贴到 Pandas 数据框中

python - recarray 中的 numpy datetime64

python - 按名称列表对 Pandas 中的多个列进行切片