简体   繁体   English

左边加入大熊猫,大致相同的数字比较

[英]left join in pandas with approximately equal numeric comparison

I am using the following to do a left join in Pandas: 我正在使用以下内容在Pandas中进行左联接:

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

however the depth_column_name and 'Core Depth' columns are floating point numbers. 但是,depth_column_name和'Core Depth'列是浮点数。 Is there a good way to do this left join such that the comparison is approximately equal such as np.isclose()? 是否有一个很好的方法来做这个左连接,使得比较大致相等,如np.isclose()?

Assuming we have the following DFs: 假设我们有以下DF:

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

Let's set joining float64 column as index (sorted): 让我们将float64列加入为索引(已排序):

In [113]: a = a.sort_values('a').set_index('a')

In [114]: b = b.assign(idx=b['a']).set_index('idx').sort_index()

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

In [116]: b
Out[116]:
         a  x
idx
1.02  1.02  Z
3.04  3.04  X
5.00  5.00  Y

now we can use DataFrame.reindex(..., method='nearest') : 现在我们可以使用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 you may want to use df.reindex(..., tolerance=<value>) parameter in order to set the tolerance: abs(index[indexer] - target) <= tolerance PS你可能想使用df.reindex(..., tolerance=<value>)参数来设置公差: abs(index[indexer] - target) <= tolerance

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM