Python Pandas匹配距离另一个Dataframe最近的索引

时间:2015-06-02 23:55:42

标签: python pandas dataframe

df.index = 10,100,1000

df2.index = 1,2,11,50,101,500,1001
Just sample

我需要匹配df2中最接近的索引与这些条件下的df匹配

  1. df2.index必须> df.index
  2. 只有一个最接近的值
  3. 例如输出

    df     |   df2
    10     |   11
    100    |   101
    1000   |   1001
    

    现在我可以用for-loop做它,它非常慢

    我使用new_df来保持索引而不是df2

    new_df2 = pd.DataFrame(columns = ["value"])
    for col in df.index:
        for col2 in df2.index:
            if(col2 > col):
                new_df2.loc[col2] = df2.loc[col2]
                break
            else:
                df2 = df2[1:] #delete first row for index speed
    

    在这种情况下如何避免for循环谢谢。

1 个答案:

答案 0 :(得分:4)

不确定这是多么强大,但您可以对df2进行排序以使其索引正在减少,并使用asof查找与{{1}中的每个键匹配的最新索引标签索引:

df