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

Pandas按其他列取值拆分单列value_counts结果为多列输出

你可以按以下步骤实现:

完整实现代码

import pandas as pd
import numpy as np

# 构造全量GPA索引(4.0到0.0,步长0.1),加round避免浮点数精度问题
full_gpa_index = np.arange(4.0, -0.1, -0.1).round(1)

# 交叉统计各GPA下运动员/非运动员的数量
count_result = pd.crosstab(
    index=students["Cumulative.GPA"],
    columns=students["Athlete"]
)

# 重命名列、补全所有GPA行、缺失值填充为0
result = count_result.rename(
    columns={
        "Yes": "Cumulative.GPA.athlete",
        "No": "Cumulative.GPA.nonathlete"
    }
).reindex(
    index=full_gpa_index,
    fill_value=0
)[["Cumulative.GPA.athlete", "Cumulative.GPA.nonathlete"]]

关键逻辑说明

  • 先用np.arange生成4.0到0.0步长0.1的全量GPA序列,加round(1)是为了规避浮点数精度误差导致的索引匹配失败问题
  • pd.crosstab可以直接统计两个维度的交叉计数,不用手动分组拆分数据
  • reindex方法可以直接把结果的行扩展为全量GPA范围,没有统计数据的位置自动填充为0,符合输出要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:57:03