用近似相等的数字比较在pandas中左连接

2024-09-28 03:12:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我用下面的方法来做熊猫的左加入:

merged_left = pd.merge(left=xrf_df,
                       right=statistics_and_notes_df, 
                       how='left', 
                       left_on=depth_column_name, 
                       right_on='Core Depth')

但是depth_column_name和“Core depth”列是浮点数。 有没有一个好的方法来做这种左连接,使比较近似相等,例如np.isclose公司()? 在


Tags: and方法namecorerightdfoncolumn
1条回答
网友
1楼 · 发布于 2024-09-28 03:12:56

假设我们有以下DFs:

In [111]: a
Out[111]:
      a  b  c
0  3.03  c  3
1  1.01  a  1
2  2.02  b  2

In [112]: b
Out[112]:
      a  x
0  1.02  Z
1  5.00  Y
2  3.04  X

让我们将连接float64列设置为索引(已排序):

^{pr2}$

现在我们可以使用DataFrame.reindex(..., method='nearest')

In [118]: a.join(b.reindex(a.index, method='nearest'), how='left')
Out[118]:
      b  c     a  x
a
1.01  a  1  1.02  Z
2.02  b  2  1.02  Z
3.03  c  3  3.04  X

In [119]: a.join(b.reindex(a.index, method='nearest'), how='left').rename(columns={'a':'a_right'})
Out[119]:
      b  c  a_right  x
a
1.01  a  1     1.02  Z
2.02  b  2     1.02  Z
3.03  c  3     3.04  X

In [120]: a.join(b.reindex(a.index, method='nearest'), how='left').rename(columns={'a':'a_right'}).reset_index()
Out[120]:
      a  b  c  a_right  x
0  1.01  a  1     1.02  Z
1  2.02  b  2     1.02  Z
2  3.03  c  3     3.04  X

PS您可能需要使用df.reindex(..., tolerance=<value>)参数来设置公差:abs(index[indexer] - target) <= tolerance

相关问题 更多 >

    热门问题