Python Pandas matching closet index from another Dataframe -


df.index = 10,100,1000  df2.index = 1,2,11,50,101,500,1001 sample 

i need match closet index df2 compare df these conditions

  1. df2.index have > df.index
  2. only 1 closet value

for example output

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

now can for-loop , it's extremely slow

and used new_df2 keep index instead of df2

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

how avoid for-loop in case thank.

not sure how robust is, can sort df2 it's index decreasing, , use asof find recent index label matching each key in df's index:

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

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -