[英]Counting the frequency in a column for a multi-index pivot table using Python
[英]Accessing multi-index value in pivot table using pandas in python
我想获得按年份分组的每个项目的销售数量总和。 所以,我为它写了下面这行:
table=pd.pivot_table(df,index=["ITEMNUMBER"],columns=["YEAR"],values=["QTY_SOLD"],aggfunc=np.sum)
我的输出是这样的:
QTY_SOLD
YEAR 2016 2017 2018 2019 2020
ITEMNUMBER
A 3.0 0.0 0.0 0.0 0.0
B 0.0 0.0 0.0 0.0 5.0
C 0.0 0.0 0.0 0.0 0.0
如何通过迭代 itemnumber 列来访问每年的数据? 我尝试重新索引,但这给了我相同的输出。
您可以删除[]以避免列中的多MultiIndex :
table=pd.pivot_table(df,index="ITEMNUMBER",columns="YEAR",values="QTY_SOLD",aggfunc=np.sum)
您的输出可能的解决方案是:
table=pd.pivot_table(df,index=["ITEMNUMBER"],columns=["YEAR"],values=["QTY_SOLD"],aggfunc=np.sum).droplevel(0, axis=1)
对于按索引和列选择使用:
for idx in table.index:
for col in table.columns:
print (table.loc[idx, col])
3.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
5.0
0.0
0.0
0.0
0.0
0.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.