如何在pydatatable中连接两个具有不同键列名称的数据框?

How to join two dataframes with different key column names in pydatatable?

我有一个 X 数据框,

DT_X = dt.Frame({
    
    'date':['2020-09-01','2020-09-02','2020-09-03'],
    'temp':[35.3,32.9,43.2]
    
})
Out[4]: 
   | date        temp
-- + ----------  ----
 0 | 2020-09-01  35.3
 1 | 2020-09-02  32.9
 2 | 2020-09-03  43.2

[3 rows x 2 columns]

另一个数据框 Y 作为,

DT_Y = dt.Frame({
    
    'stop_date' : ['2020-08-01','2020-09-01','2020-09-03','2020-09-07'],
    'is_arrested':[True,False,False,True]
    
})
Out[6]: 
   | stop_date   is_arrested
-- + ----------  -----------
 0 | 2020-08-01            1
 1 | 2020-09-01            0
 2 | 2020-09-03            0
 3 | 2020-09-07            1

[4 rows x 2 columns]

现在我想对 X 和 Y 执行 JOIN 操作,为此我应该在 X 数据帧上分配一个键,

DT_X.key='date'
Out[8]: 
date       | temp
---------- + ----
2020-09-01 | 35.3
2020-09-02 | 32.9
2020-09-03 | 43.2

[3 rows x 2 columns]

接下来我加入 X 和 Y,

DT_Y[:,:,join(DT_X)]

这里抛出一个错误,

In [9]: DT_Y[:,:,join(DT_X)]                                                                                                                                                                      
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-a3bc1690fb98> in <module>
----> 1 DT_Y[:,:,join(DT_X)]

ValueError: Key column `date` does not exist in the left Frame

当然 date 在 DT_Y 中不存在,它的列名是 stop_date

如何在这种情况下执行连接操作 ??即 列名不匹配。

:

解决此问题的方法是将 DT_Y 的列名称更改为

DT_Y.names = {'stop_date':'date'}

DT_Y[:,:,join(DT_X)]

加入的DT可以看成,

Out[11]: 
   | date        is_arrested  temp
-- + ----------  -----------  ----
 0 | 2020-08-01            1  NA  
 1 | 2020-09-01            0  35.3
 2 | 2020-09-03            0  43.2
 3 | 2020-09-07            1  NA  

[4 rows x 3 columns]

这是预期的输出:

Out[13]: 
   | stop_date   is_arrested  temp
-- + ----------  -----------  ----
 0 | 2020-08-01            1  NA  
 1 | 2020-09-01            0  35.3
 2 | 2020-09-03            0  43.2
 3 | 2020-09-07            1  NA  

[4 rows x 3 columns]

目前join()只支持在两个框架中使用相同的列名,请参考documentation for more details. However, there is an open issue改进连接functionality/API。

同时,如果您不想重命名列,您可以执行以下操作

DT_Y_date = DT_Y[:, {"date":f[0], "is_arrested":f[1]}]
DT_YX_joined = DT_Y_date[:, :, join(DT_X)]

那么,DT_YX_joined就会有你要找的数据

   | date        is_arrested  temp
-- + ----------  -----------  ----
 0 | 2020-08-01            1  NA  
 1 | 2020-09-01            0  35.3
 2 | 2020-09-03            0  43.2
 3 | 2020-09-07            1  NA 

你甚至可以one-liner喜欢

DT_YX_joined = DT_Y[:, {"date":f[0], "is_arrested":f[1]}][:, :, join(DT_X)]

但它可能不够可读。还要注意,这里没有创建数据副本,只是更改了列名。