python有多种数据合并的方法,在不同的场合我们可以使用不用的方法
一、Merge
merge可能是我们最熟悉,也最常用的一个方法,因为它的用法与mysql的连接(join)非常类似。
函数介绍
pd.merge( left, right, how=‘inner’, on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=(‘_x’, ‘_y’), copy=True, indicator=False, validate=None,)
参数详解
【常用参数】
- left: DataFrame | Series,合并的左表
- right: DataFrame | Series,合并的右表
- how: str = “inner” 合并方式,默认内连接,常用的可以改成left,左连接
- on: IndexLabel | None = None, 关联键(如果左右表名称不一样,用下面2个参数)
- left_on: IndexLabel | None = None, 左表关联键
- right_on: IndexLabel | None = None,右表关联键
- suffixes: Suffixes = (“_x”, “_y”), 左右表相同名称的变量,会自动添加后缀名
【非常用参数】
- left_index: bool = False,
- right_index: bool = False,
- sort: bool = False,
- copy: bool = True,
- indicator: bool = False,
- validate: str | None = None,
代码示例
创建示例数据
import pandas as pd
import numpy as np
left = pd.DataFrame({
'key': [1, 2, 3], 'val': ['a', 'b', 'c']})
right