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

Pandas按列统计值为1的频率并生成指定结构DataFrame

错误原因

你使用的df.groupby(1)[1].transform('count')会尝试查找名为1的列作为分组依据,而你的原始DataFrame列名为Apple、Aurora、Barn,不存在名为1的列,因此触发KeyError: 1。同时你的需求是按列统计1的占比,不需要使用行方向的分组逻辑。

实现代码

由于你的列值只有0和1,对每列直接求均值即可得到1的出现占比,再做一次结构转换就能得到目标格式的DataFrame:

import pandas as pd

# 构造原始DataFrame
d = {'Apple': [0,0,1,0,1,0], 'Aurora': [0,0,0,0,0,1], 'Barn': [0,1,1,0,0,0]}
df = pd.DataFrame(data=d)

# 统计每列1的占比,生成目标DataFrame
res_df = df.mean().reset_index(name='value')

如果后续列中存在0、1以外的数值,需要专门统计值为1的占比,可以替换为更通用的写法:

res_df = df.eq(1).mean().reset_index(name='value')

得到的res_df结构完全符合你的要求,输出示例:

indexvalue
Apple0.333333
Aurora0.166667
Barn0.333333

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:54:05