python - 对于已排序的 DataFrame,数字索引和列返回最接近传递的给定值的索引值和列名称的元组

标签 python pandas dataframe slice

我正在使用具有排序数字索引和列的 DataFrame:

    6    9    15    22
3   5    2     1     7
5   0    2     9     1
8   7    3     1     1

给定索引和列名的一些值,例如 (6, 12),我想获取原始 DataFrame 的切片:

    9    15
5   2     9
8   3     1

或者索引值,因此对于 (6, 12) 的相同示例,结果将是:

(5, 9), (8, 15)

如果输入与索引或列名称匹配,则应调整返回切片,例如对于 (8, 12),返回切片应为:

    9    15
8   3     1

在索引结果中可以解释为:

(8, 9), (8, 15)

在匹配索引和列名称的最佳情况下,例如 (8, 9),它应该是:

    9
8   3 

这可以在索引(保持一致)结果中解释为:

(8, 9), (8, 9)

最佳答案

使用一点修改this solution :

def get_closest_pair(i,c,t):
    return [(i[i <= t[0]].max(),c[c <= t[1]].max()),
            (i[i >= t[0]].min(),c[c >= t[1]].min())]

print (get_closest_pair(df.index, df.columns, (6,12)))
[(5, 9), (8, 15)]

print (get_closest_pair(df.index, df.columns, (8,12)))
[(8, 9), (8, 15)]

print (get_closest_pair(df.index, df.columns, (8,9)))
[(8, 9), (8, 9)]

关于python - 对于已排序的 DataFrame,数字索引和列返回最接近传递的给定值的索引值和列名称的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48904636/

相关文章:

dataframe - 按条件删除组

python - 将数据帧 'df1' 的字符串列与数据帧 'df2' 的另一个字符串列进行比较,在此基础上比较其他列

python - 不断收到 TypeError : 'int' object is not iterable

python - 如何一次循环n个项目而不是每次只步进1个? Python

python - 无法使用 pandas 0.17.1 附加数据帧,但可以使用 pandas 0.14.1

python - 如何使用 Pandas 处理行对并在没有字典的情况下保留 ID 列?

python - 安装 Django 的 mysql 模块

python - Windows 上程序的 CPU 使用率测量

python - 如何使用唯一ID过滤pandas数据框并在其他列上执行计算?

python - 如何 reshape DataFrame