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

如何用Pandas提取多列Yes值计数并按指定格式整理?

提取多列"Yes"值计数并整理格式的解决方案

问题背景

我使用以下代码生成计数统计:

df1 = (df.loc[df['Are you okay?']== 'No', 'Are yu sad?']
     .value_counts()
     .rename_axis('Vals')
     .reset_index(name='Count'))

目前得到的结果为:

Vals    Count
0   Yes 0.544
1   No  0.456

但实际我有3个相关列,需要提取每列的"Yes"值计数,并整理为如下格式:

Vals    Count
0   Yes     0.544
1   Yes(1)  0.032
2   Yes(2)  0.384

请问如何修改代码实现这一需求?

解决方案

假设你的3个相关列分别为'Are yu sad?'、'列名1'、'列名2'(请替换为实际列名),可通过以下代码实现需求:

# 定义目标列列表,替换为你的实际3个相关列名称
target_cols = ['Are yu sad?', '列名1', '列名2']

# 筛选指定行并统计每列中"Yes"的占比
df1 = (df.loc[df['Are you okay?'] == 'No', target_cols]
       .apply(lambda col: col.value_counts(normalize=True).get('Yes', 0))
       .reset_index()
       .rename(columns={'index': 'Vals', 0: 'Count'}))

# 为Vals列添加序号后缀,匹配目标格式
df1['Vals'] = df1['Vals'].apply(lambda x: f"Yes({target_cols.index(x)})" if target_cols.index(x) > 0 else "Yes")

代码说明

  • target_cols:务必替换成你数据中实际的3个相关列名称
  • apply(lambda col: col.value_counts(normalize=True).get('Yes', 0)):对每个目标列计算"Yes"的占比;如果需要原始计数而非占比,去掉normalize=True即可;若列中没有"Yes"值,自动返回0
  • 最后一行代码通过列在target_cols中的索引位置,为Vals列添加对应后缀,实现Yes、Yes(1)、Yes(2)的命名格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:05:13