Skip to main content
 首页 » 编程设计

python之按最近的索引加入 pandas DataFrame 值

2025年05月04日15cyq1162

加入有没有快速又好的做法pandas DataFrame最接近索引的值?我必须为大数据帧执行此操作,我尝试过的黑客攻击和变通方法很慢,因此不是很有用。

假设我有两个数据帧 df 和 df2。现在我想将 df2 的值加入到 df 中,关于它最近/最近的索引。

import numpy as np 
import pandas as pd 
 
df = pd.DataFrame(np.random.randint(0,100,size=(4, 6)),  
                index=[1,1.55,3.33,9.88],  
                columns=[1,2.66,4.66,8.33,11.11,12]) 
 
df2 = pd.DataFrame(np.random.randint(0,100,size=(2, 3)),  
                index=[1.51,3.31],  
                columns=[2.64,4.65,8.31]) 
 
In [23]: df 
Out[23]: 
 
         1.00   2.66   4.66   8.33   11.11  12.00 
1.00     98     40     28     36     49     92 
1.55     52     51     61     64     28     98 
3.33     66     33     91     21     24     79 
9.88     30     21     13     62     89     22 
 
In [24]: df2 
Out[24]: 
 
      2.64  4.65  11.12 
1.51   999   999   999 
3.31   999   999   999 
 
# The result should look like the following: 
 
         1.00   2.66   4.66   8.33   11.11  12.00 
1.00     98     40     28     36     49     92 
1.55     52     999    999    55     999    98 
3.33     66     999    999    67     999    79 
9.88     30     21     13     62     89     22 

请您参考如下方法:

设置
因为 OP 数据帧不一致

df = pd.DataFrame( 
    1, 
    index=[1,1.55,3.33,9.88], 
    columns=[1,2.66,4.66,8.33,11.11,12]) 
 
df2 = pd.DataFrame( 
    999, 
    index=[1.51,3.31], 
    columns=[2.64,4.65,8.31]) 
 
print(df) 
 
      1.00   2.66   4.66   8.33   11.11  12.00 
1.00      1      1      1      1      1      1 
1.55      1      1      1      1      1      1 
3.33      1      1      1      1      1      1 
9.88      1      1      1      1      1      1 
 
print(df2) 
 
      2.64  4.65  8.31 
1.51   999   999   999 
3.31   999   999   999 

技巧我没有时间解释。 Docs

kw = dict(method='nearest', tolerance=.3) 
df2.reindex(df.index, **kw).T.reindex(df.columns, **kw).T.combine_first(df) 
 
      1.00   2.66   4.66   8.33   11.11  12.00 
1.00    1.0    1.0    1.0    1.0    1.0    1.0 
1.55    1.0  999.0  999.0  999.0    1.0    1.0 
3.33    1.0  999.0  999.0  999.0    1.0    1.0 
9.88    1.0    1.0    1.0    1.0    1.0    1.0 

我宁愿这样做

df2.stack().reindex_like(df.stack(), **kw) 

但是我得到了:

NotImplementedError: method='nearest' not implemented yet for MultiIndex; see GitHub issue 9365

至少它会在未来的某个时候可用。