菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
1348
0

Pandas 基础 (9) - 组合方法 merge

原创
05/13 14:22
阅读数 1608

首先, 还是以天气为例, 准备如下数据:

df1 = pd.DataFrame({
    'city': ['newyork', 'chicago', 'orlando'],
    'temperature': [21, 24, 32],
})

df2 = pd.DataFrame({
    'city': ['newyork', 'chicago', 'orlando'],
    'humidity': [89, 79, 80],
})

df = pd.merge(df1, df2, on='city')

输出:

Pandas 基础(9) - 组合方法 merge

上面的例子就是以 'city' 为基准对两个 dataframe 进行合并, 但是两组数据都是高度一致, 下面调整一下:

df1 = pd.DataFrame({
    'city': ['newyork', 'chicago', 'orlando', 'baltimore'],
    'temperature': [21, 24, 32, 29],
})

df2 = pd.DataFrame({
    'city': ['newyork', 'chicago', 'san francisco'],
    'humidity': [89, 79, 80],
})

df = pd.merge(df1, df2, on='city')

输出:

Pandas 基础(9) - 组合方法 merge

从输出我们看出, 通过 merge 合并, 会取两个数据的交集.

Pandas 基础(9) - 组合方法 merge

那么, 我们应该可以设想到, 可以通过调整参数, 来达到不同的取值范围.
取并集:

df = pd.merge(df1, df2, on='city', how='outer')

输出:

Pandas 基础(9) - 组合方法 merge

左对齐:

df = pd.merge(df1, df2, on='city', how='left')

输出:

Pandas 基础(9) - 组合方法 merge

Pandas 基础(9) - 组合方法 merge

右对齐:

df = pd.merge(df1, df2, on='city', how='right')

Pandas 基础(9) - 组合方法 merge

Pandas 基础(9) - 组合方法 merge

另外, 在我们取并集的时候, 我们有时可能会想要知道, 某个数据是来自哪边, 可以通过 indicator 参数来获取:

df = pd.merge(df1, df2, on='city', how='outer', indicator=True)

输出:

Pandas 基础(9) - 组合方法 merge

在上面的例子中, 被合并的数据的列名是没有冲突的, 所以合并的很顺利, 那么如果两组数据有相同的列名, 又会是什么样呢? 看下面的例子:

df1 = pd.DataFrame({
    'city': ['newyork', 'chicago', 'orlando', 'baltimore'],
    'temperature': [21, 24, 32, 29],
    'humidity': [89, 79, 80, 69],
})

df2 = pd.DataFrame({
    'city': ['newyork', 'chicago', 'san francisco'],
    'temperature': [30, 32, 28],
    'humidity': [80, 60, 70],
})

df = pd.merge(df1, df2, on='city')

输出:

Pandas 基础(9) - 组合方法 merge

我们发现, 相同的列名被自动加上了 'x', 'y' 作为区分, 为了更直观地观察数据, 我们也可以自定义这个区分的标志:

df3 = pd.merge(df1, df2, on='city', suffixes=['_left', '_right'])

输出:

Pandas 基础(9) - 组合方法 merge

以上, 就是关于 merge 合并的相关内容。

注:Panas 系列 均是参考 Pandas Time Series Analysis 系列教程,个人觉得讲得很好。

发表评论

0/200
1348 点赞
0 评论
收藏
为你推荐 换一批