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

如何将pandas DataFrame某列取值转为新列并统计对应计数

你可以直接使用pandas的pivot_table方法实现需求,该方法原生支持分组后按指定字段拆分为多列并做聚合计数,实现代码如下:

import pandas as pd

# 原始DataFrame
df = pd.DataFrame({"person": ["Joe", "Jack", "Thomas", "Jack", "Joe", "Thomas"],
                   "fruit": ["apple", "apple", "banana", "orange", "banana", "banana"]})

# 转换逻辑
result = df.pivot_table(
    index="person",
    columns="fruit",
    aggfunc="size",
    fill_value=0
).reset_index()

执行后打印result即可得到你需要的输出格式。

如果你偏好更简洁的写法,也可以用crosstab方法直接实现交叉计数:

result = pd.crosstab(df["person"], df["fruit"]).reset_index()

如果需要提前限定输出的水果列(你提到水果类型提前已知),可以在生成结果后直接筛选指定列即可:

# 示例:仅保留指定的三列水果
result = result[["person", "apple", "banana", "orange"]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:54:03