如何用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)
最终输出
| Product | E | A | B | C |
|---|---|---|---|---|
| E | NaN | 60.0 | 65.0 | 70.0 |
| A | NaN | NaN | 10.0 | 20.0 |
| B | NaN | NaN | NaN | 50.0 |
| C | NaN | 140.0 | 9.0 | NaN |
如果需要把空值(NaN)替换成0或者其他内容,只需要在pivot_table函数里添加fill_value=0参数即可。
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

