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

使用Python统计每行array中各元素出现次数 不存在则记为0

统计数据集每行array元素出现次数实现方案

需求说明

使用Python完成以下统计需求:统计数据集中每行array内各元素的出现次数,若某元素未在对应行的array中出现,对应统计值记为0。

输入数据样例

ID                     array
0  20  [1, 2, 1, 1, 2, 3, 4, 5]
1  34     [1, 2, 2, 3, 4, 6, 7]
2  55        [6, 8, 9, 2, 1, 6]
3  66        [3, 4, 7, 7, 8, 1]

预期输出样例

ID        array              1  2   3   4   5   6   7   8  9
0   20  [1, 2, 1, 1, 2, 3, 4, 5] 3  2   1   1   1   0   0   0  0
1   34  [1, 2, 2, 3, 4, 6, 7]    1  2   1   1   0   1   1   0  0
2   55  [6, 8, 9, 2, 1, 6]       1  1   0   0   0   2   0   1  1 
3   66  [3, 4, 7, 7, 8, 1]       1  0   1   1   0   0   2   1  0

实现代码

基于pandas和collections.Counter实现,代码如下:

import pandas as pd
from collections import Counter

# 构造样例输入数据,实际使用时替换为自己的数据集读取逻辑
df = pd.DataFrame({
    'ID': [20, 34, 55, 66],
    'array': [
        [1, 2, 1, 1, 2, 3, 4, 5],
        [1, 2, 2, 3, 4, 6, 7],
        [6, 8, 9, 2, 1, 6],
        [3, 4, 7, 7, 8, 1]
    ]
})

# 获取所有array列中出现过的唯一元素,作为统计列名
all_unique_elements = sorted(set(element for arr in df['array'] for element in arr))

# 统计每行元素出现次数,未出现元素填充0
count_result = df['array'].apply(
    lambda x: pd.Series(Counter(x))
).reindex(columns=all_unique_elements, fill_value=0).astype(int)

# 合并统计结果到原数据表
final_df = pd.concat([df, count_result], axis=1)

# 打印输出结果
print(final_df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 05:18:03