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

统计DataFrame中各element的总出现次数、正确次数与错误次数

Pandas按Element统计总次数及正误次数

给定如下Pandas DataFrame数据,需要按element字段分组,统计每个element的总出现次数、code == test的正确次数,以及code != test的错误次数。

原始DataFrame:

customerId                text element  code  test
0           1  Something with Cat     cat     9     9
1           3  That is a huge dog     dog     8   999
2           3         Hello agian   mouse     7     7
3           3        This is a ca     cat     9   999
4           3       this is a cad     cat     9     9

构造DataFrame的代码:

import pandas as pd
d = {
    "customerId": [1, 3, 3, 3, 3],
    "text": ["Something with Cat", "That is a huge dog", "Hello agian", 'This is a ca', 'this is a cad'],
     "element": ['cat', 'dog', 'mouse', 'cat', 'cat'],
     "code": [9,8,7, 9, 9],
     "test": [9,999,7,999,9]
}
df = pd.DataFrame(data=d)

期望输出格式:

element     count_complete count_true  count_false
cat         3              2           1
dog         1              0           1
mouse       1              1           0

解决方案

通过新增标记列+分组聚合的方式实现:

# 新增列标记code与test是否匹配
df['is_true'] = df['code'] == df['test']

# 分组聚合统计各项指标
result = df.groupby('element').agg(
    count_complete=('element', 'size'),
    count_true=('is_true', 'sum'),
    count_false=('is_true', lambda x: len(x) - x.sum())
).reset_index()

# 按期望格式打印结果
print(result.to_string(index=False))

执行后输出:

element  count_complete  count_true  count_false
    cat                3           2            1
    dog                1           0            1
  mouse                1           1            0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 10:48:17