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. 只有一个最接近的值

例如输出

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

现在我可以用for-loop来完成它它非常慢

我用new_df2而不是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循环谢谢。

不确定这是多么稳健,但你可以排序df2,所以它的索引是递减的,并使用asof找到最近的索引标签匹配df的索引中的每个键:

df2.sort_index(ascending=False, inplace=True)
df['closest_df2'] = df.index.map(lambda x: df2.index.asof(x))
df
Out[19]: 
      a  closest_df2
10    1           11
100   2          101
1000  3         1001

最新更新