基于多列合并 Pandas DataFrames 的实用指南

本文档详细介绍了如何使用 Pandas 库基于多个列来合并两个 DataFrames。我们将探讨使用 `merge` 函数的不同方法,包括处理缺失值和排序结果,以生成满足特定需求的合并数据集。通过学习本文,你将掌握高效的数据合并技巧,为后续的数据分析和处理打下坚实基础。

在数据分析和处理中,经常需要将来自不同来源的数据集合并成一个统一的数据集。Pandas 库提供了强大的 merge 函数,可以根据一个或多个列将两个 DataFrames 连接起来。本文将详细介绍如何使用 merge 函数,并提供一些实用的技巧和示例。

使用 merge 函数进行外连接

最直接的方法是使用 pandas.merge 函数执行外连接(outer join)。外连接会保留两个 DataFrame 中的所有行,并在缺失值的地方填充 NaN。为了区分左右 DataFrame 的列名,我们可以使用 add_suffix 函数为列名添加后缀。

import pandas as pd

# 示例数据
df1 = pd.DataFrame({
    'level': ['Level 0', 'Level 1', 'Level 1', 'Level 1', 'Level 2', 'Level 2', 'Level 3'],
    'title': ['Effective', 'Evaluation', 'Ice Breaker', 'Fire', 'Introduction', 'Understanding', 'Connect']
})

df2 = pd.DataFrame({
    'level': ['Level 0', 'Level 1', 'Level 1', 'Level 2', 'Level 2', 'Level 4'],
    'title': ['Effective', 'Evaluation', 'Comedy', 'Introduction', 'Understanding', 'Connect']
})

# 使用 merge 进行外连接,并添加后缀
out = df1.merge(df2.add_suffix('_'), how='outer',
                left_on=['level', 'title'],
                right_on=['level_', 'title_'])

print(out)

输出结果如下:

     level          title   level_         title_
0  Level 0      Effective  Level 0      Effective
1  Level 1     Evaluation  Level 1     Evaluation
2  Level 1    Ice Breaker      NaN            NaN
3  Level 1           Fire      NaN            NaN
4  Level 2   Introduction  Level 2   Introduction
5  Level 2  Understanding  Level 2  Understanding
6  Level 3        Connect      NaN            NaN
7      NaN            NaN  Level 1         Comedy
8      NaN            NaN  Level 4        Connect

对合并后的结果进行排序

如果需要对合并后的结果进行排序,可以使用 sort_values 函数。在这种情况下,我们不需要手动添加后缀,可以直接在 left_on 和 right_on 参数中指定要合并的列。

import pandas as pd

# 示例数据
df1 = pd.DataFrame({
    'level': ['Level 0', 'Level 1', 'Level 1', 'Level 1', 'Level 2', 'Level 2', 'Level 3'],
    'title': ['Effective', 'Evaluation', 'Ice Breaker', 'Fire', 'Introduction', 'Understanding', 'Connect']
})

df2 = pd.DataFrame({
    'level': ['Level 0', 'Level 1', 'Level 1', 'Level 2', 'Level 2', 'Level 4'],
    'title': ['Effective', 'Evaluation', 'Comedy', 'Introduction', 'Understanding', 'Connect']
})

# 使用 merge 进行外连接,并排序
out = (df1.merge(df2, how='outer',
                 left_on=[df1['level'], df1['title']],
                 right_on=['level', 'title'])
          .sort_values(by=['level'])
      )

print(out)

输出结果如下:

     level          title level_x      title_x level_y    title_y
0  Level 0      Effective Level 0  Effective Level 0  Effective
1  Level 1     Evaluation Level 1 Evaluation Level 1 Evaluation
2  Level 1    Ice Breaker Level 1 Ice Breaker     NaN        NaN
3  Level 1           Fire Level 1      Fire     NaN        NaN
7  Level 1         Comedy     NaN        NaN Level 1     Comedy
4  Level 2   Introduction Level 2 Introduction Level 2 Introduction
5  Level 2  Understanding Level 2 Understanding Level 2 Understanding
6  Level 3        Connect Level 3    Connect     NaN        NaN
8  Level 4        Connect     NaN        NaN Level 4    Connect

清理结果

如果需要删除重复的列,可以取消注释代码中的 .drop(columns=['level', 'title']) 行。这将删除用于合并的原始列,只保留带有后缀的列。

注意事项

  • 确保要合并的列具有相同的数据类型。如果数据类型不匹配,可能会导致合并失败或产生意外的结果。
  • 如果两个 DataFrame 中存在相同的列名,merge 函数会自动为右侧 DataFrame 的列名添加后缀。可以通过 suffixes 参数自定义后缀。
  • how 参数指定了合并的方式。除了 outer,还可以使用 inner(内连接)、left(左连接)和 right(右连接)。
  • 在处理大型数据集时,合并操作可能会比较耗时。可以考虑使用 dask 等分布式计算框架来加速合并过程。

总结

本文介绍了如何使用 Pandas 库基于多个列来合并两个 DataFrames。通过掌握 merge 函数的不同用法,可以灵活地处理各种数据合并场景。在实际应用中,需要根据具体的需求选择合适的合并方式和参数,并注意数据类型和性能优化等问题。