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

如何使用Python Pandas按标签匹配值并统计匹配次数

需求说明

现有如下结构的CSV数据:

marktimevalue1value2
114:22:0252
114:22:0584
214:25:0211
214:26:0547
315:12:0852
315:12:1154
315:12:1552
315:12:1784

需使用Python Pandas针对mark=1和mark=3的数据进行值匹配统计:即统计mark=1中出现的(组合或单列)值,在mark=3对应列中的出现次数,最终输出三类统计结果。

实现代码
import pandas as pd

# 加载数据(也可通过pd.read_csv('你的文件路径.csv')读取本地CSV)
data = [
    [1, "14:22:02", 5, 2],
    [1, "14:22:05", 8, 4],
    [2, "14:25:02", 1, 1],
    [2, "14:26:05", 4, 7],
    [3, "15:12:08", 5, 2],
    [3, "15:12:11", 5, 4],
    [3, "15:12:15", 5, 2],
    [3, "15:12:17", 8, 4]
]
df = pd.DataFrame(data, columns=['mark', 'time', 'value1', 'value2'])

# 筛选目标标签数据
df_mark1 = df[df['mark'] == 1]
df_mark3 = df[df['mark'] == 3]

# 1. 按value1与value2组合统计
counts_combined = df_mark3.groupby(['value1', 'value2']).size().reset_index(name='Number of matches')
result_combined = counts_combined.merge(df_mark1[['value1', 'value2']], on=['value1', 'value2'], how='right')
result_combined['mark'] = '1-3'
result_combined = result_combined[['mark', 'value1', 'value2', 'Number of matches']]

# 2. 按value1单列统计
counts_value1 = df_mark3.groupby('value1').size().reset_index(name='Number of matches')
result_value1 = counts_value1.merge(df_mark1[['value1']], on='value1', how='right')
result_value1['mark'] = '1-3'
result_value1 = result_value1[['mark', 'value1', 'Number of matches']]

# 3. 按value2单列统计
counts_value2 = df_mark3.groupby('value2').size().reset_index(name='Number of matches')
result_value2 = counts_value2.merge(df_mark1[['value2']], on='value2', how='right')
result_value2['mark'] = '1-3'
result_value2 = result_value2[['mark', 'value2', 'Number of matches']]

# 打印结果
print("按value1与value2组合统计:")
print(result_combined)
print("\n按value1单列统计:")
print(result_value1)
print("\n按value2单列统计:")
print(result_value2)
统计结果

1. 按value1与value2两列组合统计

markvalue1value2Number of matches
1-3522
1-3841

2. 按value1单列统计

markvalue1Number of matches
1-353
1-381

3. 按value2单列统计

markvalue2Number of matches
1-322
1-342

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:48:19