gpt4 book ai didi

python - 强制额外的列显示在 pandas 数据透视表中?

转载 作者:行者123 更新时间:2023-11-30 22:19:16 26 4
gpt4 key购买 nike

是否可以强制 Pandas 在数据透视表中包含一组特定的有序列,而不管基础数据是否保证它们的存在?例如

df = pd.DataFrame({'Project': ['ProjectA', 'ProjectB', 'ProjectC'],
'Start Month': [2,5,9],
'End Month': [3,7,10],
'Category': ['A', 'B', 'A']
})
pv = pd.pivot_table(df, values='Project', index='Category', columns='Start Month', aggfunc={'Project':lambda x: "".join(x) }).fillna('')

产生

Start Month  2          5         9
Category
A ProjectA ProjectC
B ProjectB

但我想要的是查看 12 个月中每一个月的列,即使那里没有数据:

Start Month  1  2         3  4  5        6  7  8  9         10  11  12
Category
A ProjectA ProjectC
B ProjectB

这在数据具有底层自然排序和呈现表示形式(例如逐月日历)的情况下非常有用。

最佳答案

只需在列上重新索引?

pv.reindex(columns=np.arange(1, 13), fill_value='')

Start Month 1 2 3 4 5 6 7 8 9 10 11 12
Category
A ProjectA ProjectC
B ProjectB

关于python - 强制额外的列显示在 pandas 数据透视表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49178331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com