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

如何用Pandas创建行与列仅含指定列表值的Pivot Table?

解决方案

完全可以创建符合要求的透视表,具体操作如下:

  • 第一步:过滤无效数据:把Product或things不在current_list里的行删掉(比如原数据里包含D的行,D不在指定列表中,属于无效数据)
  • 第二步:生成透视表并调整索引列:以Product为索引、things为列、Marks2为值生成透视表,再强制把索引和列的范围限定为current_list的内容,确保顺序和指定列表一致

完整代码

import pandas as pd

# 初始化原数据
df1 = pd.DataFrame({'Product':['A','A','A','B','B','C','C','C','E','E','E'],
                    'things':['B','C','D','C','D','D','A','B','A','B','C'],'Marks2':[10,20,6,50, 88,23,140,9,60,65,70]})

current_list = ['E', 'A', 'B', 'C']

# 过滤出仅包含current_list元素的有效行
filtered_df = df1[(df1['Product'].isin(current_list)) & (df1['things'].isin(current_list))]

# 创建透视表,并重索引匹配指定的索引和列
pivot_table = filtered_df.pivot_table(
    index='Product',
    columns='things',
    values='Marks2',
    aggfunc='first'  # 因为每个Product+things组合只有一个值,用first直接取
).reindex(index=current_list, columns=current_list)

print(pivot_table)

最终输出

ProductEABC
ENaN60.065.070.0
ANaNNaN10.020.0
BNaNNaNNaN50.0
CNaN140.09.0NaN

如果需要把空值(NaN)替换成0或者其他内容,只需要在pivot_table函数里添加fill_value=0参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:16:21