You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何找出两个DataFrame中coin所属country变更的差异行?

识别DataFrame中硬币所属国家变更的行

假设我们有两个DataFrame:

  • 原始数据(记录硬币初始所属国家):
countrycoin
USAcoin1
USAcoin2
Mexicocoin3
  • 变更后数据(记录硬币更新后的所属国家):
countrycoin
USAcoin1
Mexicocoin2
Mexicocoin3

由于每个coin是唯一标识,我们可以通过对比同一硬币在两个表中的country值,找出发生变更的行。以下是基于Pandas的实现方法:

import pandas as pd

# 构建原始DataFrame
df_old = pd.DataFrame({
    'country': ['USA', 'USA', 'Mexico'],
    'coin': ['coin1', 'coin2', 'coin3']
})

# 构建变更后DataFrame
df_new = pd.DataFrame({
    'country': ['USA', 'Mexico', 'Mexico'],
    'coin': ['coin1', 'coin2', 'coin3']
})

# 以coin为键合并两个表,区分前后的country列
merged_df = df_old.merge(df_new, on='coin', suffixes=('_old', '_new'))

# 筛选出国家发生变更的行,提取变更后的信息
changed_records = merged_df[merged_df['country_old'] != merged_df['country_new']][['country_new', 'coin']]

# 重命名列名匹配期望输出格式
changed_records = changed_records.rename(columns={'country_new': 'country'})

print(changed_records)

运行后输出结果:

countrycoin
Mexicocoin2

核心思路

  1. 利用coin的唯一性作为关联键,合并原始与变更后的数据集;
  2. 通过对比country_old和country_new两列,筛选出值不相等的行;
  3. 提取变更后的国家信息与对应硬币,得到最终结果。

内容的提问来源于stack exchange,提问作者Vinícius Tomazoni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:50:51