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

如何将DataFrame的keywords与Count列转换为宽表格式

实现DataFrame长表转宽表的方法

直接用pandas的pivot函数就能完成这个转换,具体操作如下:

  1. 假设你已经有了目标DataFrame(命名为df),执行以下代码:
import pandas as pd

# 构造示例数据(已有数据可跳过此部分)
data = {
    'Name': ['User1', 'User1', 'User1', 'User2', 'User2', 'User2', 'User3', 'User3', 'User3'],
    'keywords': ['aws', 'ec2', 'python', 'aws', 'ec2', 'python', 'aws', 'ec2', 'python'],
    'Count': [14, 4, 1, 12, 5, 6, 17, 7, 8]
}
df = pd.DataFrame(data)

# 执行转换
result_df = df.pivot(index='Name', columns='keywords', values='Count').reset_index()
# 移除列索引的名称,避免出现多余的表头标识
result_df = result_df.rename_axis(None, axis=1)

print(result_df)
  1. 输出结果如下:
Name  aws  ec2  python
0  User1   14    4       1
1  User2   12    5       6
2  User3   17    7       8

如果需要固定列的显示顺序(比如保持aws、ec2、python的顺序),可以在转换后指定列序列:

result_df = result_df[['Name', 'aws', 'ec2', 'python']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:45:35