在浮点值列上合并 Pandas DataFrame [英] Merge pandas DataFrame on column of float values

查看:27
本文介绍了在浮点值列上合并 Pandas DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个要合并的数据框.

I have two data frames that I am trying to merge.

数据框 A:

    col1    col2    sub    grade
0   1       34.32   x       a 
1   1       34.32   x       b
2   1       34.33   y       c
3   2       10.14   z       b
4   3       33.01   z       a

数据框 B:

    col1    col2    group   ID
0   1       34.32   t       z 
1   1       54.32   s       w
2   1       34.33   r       z
3   2       10.14   q       z
4   3       33.01   q       e

我想在 col1 和 col2 上合并.我已经 pd.merge 使用以下语法:

I want to merge on col1 and col2. I've been pd.merge with the following syntax:

pd.merge(A, B, how = 'outer', on = ['col1', 'col2'])

但是,我想我在加入 col2 的浮点值时遇到了问题,因为很多行都被删除了.有没有办法使用 np.isclose 来匹配 col2 的值?当我在任一数据框中引用 col2 的特定值的索引时,该值的小数位数比数据框中显示的要多得多.

However, I think I am running into issues joining on the float values of col2 since many rows are being dropped. Is there any way to use np.isclose to match the values of col2? When I reference the index of a particular value of col2 in either dataframe, the value has many more decimal places than what is displayed in the dataframe.

我希望结果是:

    col1   col2   sub   grade   group    ID
0   1      34.32  x     a       t        z
1   1      34.32  x     b       s        w
2   1      54.32  s     w       NaN      NaN
3   1      34.33  y     c       r        z
4   2      10.14  z     b       q        z
5   3      33.01  z     a       q        e

推荐答案

你可以使用一个小技巧——多个浮点列通过一些常量,比如 100, 1000...,将列转换为intmerge,最后除以常量:

You can use a little hack - multiple float columns by some constant like 100, 1000..., convert column to int, merge and last divide by constant:

N = 100
#thank you koalo for comment
A.col2 = np.round(A.col2*N).astype(int) 
B.col2 = np.round(B.col2*N).astype(int) 
df = pd.merge(A, B, how = 'outer', on = ['col1', 'col2'])
df.col2 = df.col2 / N
print (df)
   col1   col2  sub grade group ID
0     1  34.32    x     a     t  z
1     1  34.32    x     b     t  z
2     1  34.33    y     c     r  z
3     2  10.14    z     b     q  z
4     3  33.01    z     a     q  e
5     1  54.32  NaN   NaN     s  w

这篇关于在浮点值列上合并 Pandas DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆