根据2个键合并pandas df

时间:2018-02-02 14:41:29

标签: python pandas merge

我有2个df,我想根据2个键合并它们 - ID和日期: 我跟随的只是整个df的一小部分

df_pw6

ax3

df_ex

class MyPrinter:
        def __init__(self, val):
                self.val = val

        def to_hex(self, val):
                s = ''
                x = 7
                while (x >= 0):
                        s = s + "%02x" % ((val>>(x*8))&255)
                        x -= 1

                return s

        def to_string(self):
                return self.to_hex(self.val['fData'][0]) + self.to_hex(self.val['fData'][1])

如您所见,只有第三行有匹配。 当我输入:

     ID     date           pw10_0        pw50_0     pw90_0
0   153     2018-01-08     27.88590     43.2872     58.2024
0   2       2018-01-05     11.03610     21.4879     31.6997
0   506     2018-01-08     6.98468      25.3899     45.9486

现在我尝试合并它们:

    date         ID   measure f188  f187  f186  f185
0   2017-07-03  501     NaN     1   0.5     7   4.0
1   2017-07-03  502     NaN     0   2.5     5   3.0
2   2018-01-08  506     NaN     5   9.0     9   1.2

我得到一个空的df

当我尝试:

#check date
df_ex.iloc[2,0]== df_pw6.iloc[1,1]
True

#check ID
df_ex.iloc[2,1] == df_pw6.iloc[2,0]
True

我明白了:

df19 = pd.merge(df_pw6,df_ex,on=['date','ID'])

我想要的结果应该是:

df19 = pd.merge(df_pw6,df_ex,how ='left',on=['date','ID'])

1 个答案:

答案 0 :(得分:0)

我在编辑后运行了您的代码,我成功获得了所需的结果。

import pandas as pd

# copy paste your first df by hand
pw = pd.read_clipboard()

# copy paste your second df by hand
ex = pd.read_clipboard()

pd.merge(pw,ex,on=['date','ID'])
# output [edited. now it is the correct result OP wanted.]

    ID        date   pw10_0   pw50_0   pw90_0  measure  f188  f187  f186  f185
0  506  2018-01-08  6.98468  25.3899  45.9486      NaN     5   9.0     9   1.2