如何使用Python Pandas按标签匹配值并统计匹配次数
需求说明
现有如下结构的CSV数据:
| mark | time | value1 | value2 |
|---|---|---|---|
| 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 |
需使用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两列组合统计
| mark | value1 | value2 | Number of matches |
|---|---|---|---|
| 1-3 | 5 | 2 | 2 |
| 1-3 | 8 | 4 | 1 |
2. 按value1单列统计
| mark | value1 | Number of matches |
|---|---|---|
| 1-3 | 5 | 3 |
| 1-3 | 8 | 1 |
3. 按value2单列统计
| mark | value2 | Number of matches |
|---|---|---|
| 1-3 | 2 | 2 |
| 1-3 | 4 | 2 |
内容的提问来源于stack exchange,提问作者Genry
相关产品推荐
相关产品推荐

