
在数据分析中,经常需要比较两个结构相似但内容可能存在差异的DataFrame,例如比较当前估算与历史估算数据。Pandas提供了强大的合并(merge)功能,结合特定的参数,可以轻松实现这一目标。
核心方法是使用pd.merge函数,并设置how='outer'和indicator=True。
通过筛选_merge列不为'both'的行,我们就能得到所有存在差异的行。
示例代码:识别差异行并标注来源
假设我们有两个DataFrame,df_current_est代表当前估算,df_previous_est代表历史估算。
import pandas as pd
# 模拟数据
df_current_est = pd.DataFrame({
'EstimateID': [10061, 10062, 10063],
'Season': [2023, 2023, 2023],
'RPIN': ['R1000', 'R2000', 'R3000'],
'GrowMethodCode': ['FO', 'FO', 'FO'],
'Variety_code': ['002', '068', '001'],
'Packout_pc': [0.60, 0.76, 0.80],
'QtyBins': [320, 1000, 500]
})
df_previous_est = pd.DataFrame({
'EstimateID': [10061, 10062, 10064],
'Season': [2023, 2023, 2023],
'RPIN': ['R1000', 'R2000', 'R4000'],
'GrowMethodCode': ['FO', 'FO', 'FO'],
'Variety_code': ['002', '068', '003'],
'Packout_pc': [0.60, 0.76, 0.90],
'QtyBins': [9000, 90000, 600]
})
print("df_current_est:")
print(df_current_est)
print("\ndf_previous_est:")
print(df_previous_est)
# 执行外连接并添加指示器
merged_df = pd.merge(df_current_est, df_previous_est, how='outer', indicator=True)
# 筛选出存在差异的行(即不完全匹配的行)
changed_df = merged_df[merged_df['_merge'] != 'both'].copy()
# 打印结果,_merge列清晰地指示了行的来源
print("\n差异行及其来源:")
print(changed_df)输出解释: 在上述示例中,changed_df将包含所有在df_current_est和df_previous_est之间不完全匹配的行。_merge列的值(left_only或right_only)明确告诉我们该差异行是来自当前估算还是历史估算。例如,如果EstimateID为10061的行在df_current_est中QtyBins为320,而在df_previous_est中QtyBins为9000,那么即使其他列相同,由于QtyBins不同,这两行也会被视为差异,并分别显示为left_only和right_only。
注意事项:
在某些情况下,除了知道差异行来自哪个DataFrame外,我们可能还需要知道这些差异行在原始DataFrame中的具体行索引。_merge列本身不保留原始的行索引信息,因为它生成的是一个新的DataFrame。为了追踪原始索引,我们需要在合并之前将索引转换为普通列。
示例代码:保留原始索引
import pandas as pd
# 模拟数据,带有自定义索引
df1 = pd.DataFrame({'key': ['one', 'two', 'three'], 'value1': [1, 2, 3]},
index=[101, 102, 103])
df2 = pd.DataFrame({'key': ['two', 'four', 'three'], 'value2': [20, 40, 30]},
index=[201, 202, 203])
print("df1 (带索引):")
print(df1)
print("\ndf2 (带索引):")
print(df2)
# 在合并前将索引重置为列,并指定后缀以区分
merged_df_with_indices = (
pd.merge(df1.reset_index(), # 将df1的索引转换为'index'列
df2.reset_index(), # 将df2的索引转换为'index'列
on='key', # 以'key'列为基准进行合并
suffixes=('_df1', '_df2'), # 为重复列名(包括'index')添加后缀
how='outer',
indicator=True)
)
# 筛选出差异行
changed_df_with_indices = merged_df_with_indices.query('_merge != "both"')
print("\n差异行及其来源和原始索引:")
print(changed_df_with_indices)输出解释: 在这个例子中:
通过本教程,我们学习了如何利用pd.merge函数的how='outer'和indicator=True参数来有效地识别Pandas DataFrame之间的差异行,并清晰地追溯每条差异行的原始来源。此外,我们还探讨了通过在合并前重置索引的方法,来保留并追踪差异行在原始DataFrame中的具体行索引,这对于需要回溯数据源的复杂分析场景至关重要。掌握这些技巧,将极大地提升您在处理和比较DataFrame数据时的效率和准确性。
以上就是Pandas DataFrame差异识别与来源追溯教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号