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

如何用Pandas统计类型数量并将数据转换为宽格式

解决方案

有两种高效的方法可以实现你的需求,都是Pandas内置的函数,代码简洁且性能优秀:

方法1:使用pd.crosstab(最直接)

crosstab专门用于计算两列的交叉频数表,一步就能生成目标格式:

import pandas as pd

# 基于你已提取的df_Type生成结果
result = pd.crosstab(
    index=df_Type['Type 1'],
    columns=df_Type['Generation'],
    rownames=['Type'],
    colnames=['Generation']
).rename(columns=lambda x: f'Generation {x}').reset_index()

# 若需要确保缺失计数填充为0,可添加fill_value=0参数
# result = pd.crosstab(df_Type['Type 1'], df_Type['Generation'], fill_value=0, rownames=['Type'], colnames=['Generation']).rename(columns=lambda x: f'Generation {x}').reset_index()

print(result)

输出结果与目标格式完全一致:

Type  Generation 1  Generation 2  Generation 3
0  Grass              2             1             1
1   Fire              2             0             0

方法2:使用groupby + pivot

先分组统计数量,再重塑为宽表,逻辑更直观:

# 第一步:统计每种Type对应各Generation的数量
count_df = df_Type.groupby(['Type 1', 'Generation']).size().reset_index(name='Count')

# 第二步:转成宽格式,填充缺失值并调整列名
result = count_df.pivot(
    index='Type 1',
    columns='Generation',
    values='Count'
).fillna(0).astype(int).rename(columns=lambda x: f'Generation {x}').reset_index().rename(columns={'Type 1': 'Type'})

print(result)

你之前的代码问题说明

你写的groupby('Generation').agg(no_types = ('Type 1', 'sum'))有两个核心问题:

  • 分组维度错误:仅按Generation分组,没有同时按Type分组,无法拆分出每种Type的各代数量
  • 聚合函数错误:sum会对字符串类型的Type 1列做拼接,不是统计数量,应该用size()或count()实现计数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:30:50