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

如何在pandas中统计DataFrame二维列表列对应类别的非空非零元素数

问题原因

你写的代码存在两处错误:

  • 原生Python没有直接调用count()统计生成器元素数量的语法,你需要用sum()统计符合条件的布尔值总和(布尔值True对应1、False对应0,求和结果就是符合条件的元素个数)
  • 过滤逻辑错误:你原来的if v and v!=0是判断子列表本身不为0,实际需要判断子列表对应位置的得分不为0

修正后代码

首先完成score列的类型转换:

import pandas as pd
from ast import literal_eval

# 构造初始DataFrame
df = pd.DataFrame({
    'text':['No thank you', 'They didnt respond me'],
    'pred':['positive', 'negative'],
    'score':["[[0, 0, 1], [1, 0, 2], [1, 0, 0]]", "[[], [0, 1, 0], [], []]"] 
})

# 转换score列为列表类型
df["score"] = df["score"].apply(literal_eval)

然后实现计数逻辑:

m_sum = {"positive": 0, "negative": 1, "neutral": 2}
df["count"] = df.apply(
    lambda x: sum(v[m_sum[x["pred"]]] != 0 for v in x["score"] if v),
    axis=1
)

也可以写成更直观的写法,效果完全一致:

df["count"] = df.apply(
    lambda x: sum(1 for v in x["score"] if v and v[m_sum[x["pred"]]] != 0),
    axis=1
)

输出验证

运行后得到的结果和预期完全匹配:

textpredscorecount
No thank youpositive[[0, 0, 1], [1, 0, 2], [1, 0, 0]]2
They didnt respond menegative[[], [0, 1, 0], [], []]1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:09:04