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

如何用Pandas合并3个DataFrame并统计重复行出现次数?

用Pandas统计行数据在多个DataFrame中的出现次数

我有3个如下的DataFrame:

DataFrame 1

Hours | Country | Event
----------------------- 
02:00 |   BR    | Sleeping
09:00 |   GB    | Breakfast
09:30 |   IT    | Meeting
12:00 |   CA    | Lunch Time
15:00 |   RU    | Working
16:00 |   CO    | Salsa Dance
18:00 |   CN    | Happy Hour
21:00 |   US    | Easter
22:00 |   FR    | Shopping

DataFrame 2

Hours | Country | Event 
-----------------------
02:00 |   BR    | Sleeping
09:00 |   GB    | Breakfast
09:30 |   IT    | Meeting
15:00 |   RU    | Working
16:00 |   CO    | Salsa Dance
18:00 |   CN    | Happy Hour

DataFrame 3

Hours | Country | Event
----------------------- 
02:00 |   BR    | Sleeping
09:30 |   IT    | Meeting
16:00 |   CO    | Salsa Dance

想要得到第四个DataFrame,统计每行在三个DataFrame中重复出现的次数,并将次数存入新列Count,预期结果如下:

预期结果(DataFrame 4)

Hours | Country | Event        | Count 
--------------------------------------
02:00 |   BR    | Sleeping     |   3
09:00 |   GB    | Breakfast    |   2
09:30 |   IT    | Meeting      |   3
12:00 |   CA    | Lunch Time   |   1
15:00 |   RU    | Working      |   2
16:00 |   CO    | Salsa Dance  |   3
18:00 |   CN    | Happy Hour   |   2
21:00 |   US    | Easter       |   1
22:00 |   FR    | Shopping     |   1

实现方法

不用嵌套循环,用Pandas的内置函数就能高效解决,步骤如下:

  1. 合并所有DataFrame:用pd.concat()把三个DataFrame合并成一个整体
  2. 分组统计次数:以Hours、Country、Event三列为分组依据,用groupby().size()统计每组的出现次数
  3. 整理结果格式:将统计结果的索引重置为普通列,并把统计列命名为Count

完整代码示例:

import pandas as pd

# 创建示例DataFrame
df1 = pd.DataFrame({
    'Hours': ['02:00', '09:00', '09:30', '12:00', '15:00', '16:00', '18:00', '21:00', '22:00'],
    'Country': ['BR', 'GB', 'IT', 'CA', 'RU', 'CO', 'CN', 'US', 'FR'],
    'Event': ['Sleeping', 'Breakfast', 'Meeting', 'Lunch Time', 'Working', 'Salsa Dance', 'Happy Hour', 'Easter', 'Shopping']
})

df2 = pd.DataFrame({
    'Hours': ['02:00', '09:00', '09:30', '15:00', '16:00', '18:00'],
    'Country': ['BR', 'GB', 'IT', 'RU', 'CO', 'CN'],
    'Event': ['Sleeping', 'Breakfast', 'Meeting', 'Working', 'Salsa Dance', 'Happy Hour']
})

df3 = pd.DataFrame({
    'Hours': ['02:00', '09:30', '16:00'],
    'Country': ['BR', 'IT', 'CO'],
    'Event': ['Sleeping', 'Meeting', 'Salsa Dance']
})

# 合并三个DataFrame
combined_df = pd.concat([df1, df2, df3])

# 分组统计次数并整理格式
result_df = combined_df.groupby(['Hours', 'Country', 'Event']).size().reset_index(name='Count')

# 查看结果
print(result_df)

说明

这种方法利用Pandas的向量化操作,比手动嵌套循环效率高得多,尤其是处理大规模数据时优势明显。分组统计会自动识别所有唯一的行,并计算它们在三个原DataFrame中的总出现次数,完全匹配预期结果。

内容的提问来源于stack exchange,提问作者Bruce Ecurb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 09:57:43