Python Pandas-在多列上向左连接,在最终数据框中添加空格

时间:2018-07-24 17:04:11

标签: python pandas merge

我正在尝试通过以下方式进行多重联接:

host_data = temp_merged_data.merge(desc_data, left_on=['device_id, port'], how='left')

但是收到错误:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/pandas/core/frame.py", line 6389, in merge
    copy=copy, indicator=indicator, validate=validate)
  File "/usr/local/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 61, in merge
    validate=validate)
  File "/usr/local/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 546, in __init__
    self._validate_specification()
  File "/usr/local/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 1059, in _validate_specification
    if len(self.right_on) != len(self.left_on):
TypeError: object of type 'NoneType' has no len()

temp_merged_data示例:

   mac_address  device_id device_type     ip_address      port  vlan
0000.001d.f805        304      Switch    10.10.10.1      None   5.0
0000.001d.f10a         89      Router  10.10.10.129      None   10.0
0000.001d.f0a3         89      Router  10.10.10.193      None   15.0
0000.001d.f024        303      Switch  10.10.10.225     Gi0/23  20.0
0101.001d.79a2        303      Switch   10.10.10.26     Gi0/3   5.0

desc_data示例:

                description  device_id device_type mac_address      port
    *** UPLINK to SW-03 ***        303      Switch                Gi0/23
       *** UPLINK to SW ***        303      Switch                Gi0/24
               *** CCTV ***        304      Switch                Gi0/21
    *** UPLINK to SW-03 ***        304      Switch                Gi0/23
       *** UPLINK to SW ***        304      Switch                Gi0/24

如果端口描述不存在,我希望能够将端口描述合并到temp_mergedata框架中。

谢谢

1 个答案:

答案 0 :(得分:2)

host_data = temp_merged_data.merge(desc_data, left_on=['device_id', 'port'], how='left', right_on=['device_id', 'port'])

或如@Scott所建议,如果字段列表相同

host_data = temp_merged_data.merge(desc_data, on=['device_id', 'port'], how='left')