python - Python Pivot 丢失最后一列
问题描述
我正在打开一个 .csv 并用 pandas 命名它 pull :
Quarter Category Value
7776 Q1-17 Autos and Transportation 6997035.2
7777 Q2-17 Autos and Transportation 7897574.5
7778 Q3-17 Autos and Transportation 6983654.1
7779 Q4-17 Autos and Transportation 7301336.9
7780 Q1-18 Autos and Transportation 7627895.3
有 6 个不同的类别,我想将其结构化为:
Quarter Q2-17 Q3-17 Q4-17 Q1-18
Category
Autos and Transportation 12196407.0 13591411.0 14757349.0 15735009.0
Building and Construction 7446408.5 7873713.2 9360943.1 9355093.8
Business and Industry 9871899.8 10264492.0 9640937.3 10668084.0
Food and Drugs 4287428.7 4363061.2 4528251.5 4605146.4
Fuel and Service Stations 9551811.4 8637092.7 7649205.4 7542200.1
General Consumer Goods 18120167.0 19035865.0 19692248.0 19775445.0
Restaurants and Hotels 8138913.7 9021774.4 9712391.4 10649011.0
Total 76758539.0 81455234.0 84251489.0 87868048.0
我试图通过写来做到这一点:
reshape = pull.pivot(index='Category', columns='Quarter', values='Value')
除了我丢失了最后一列“Q1-18”之外它有效。知道如何保留所有列吗?
print(reshape.tail(4))
Quarter Q4-13 Q4-14 Q4-15 Q4-16 \
Category
Fuel and Service Stations 9551811.4 8637092.7 7649205.4 7542200.1
General Consumer Goods 18120167.0 19035865.0 19692248.0 19775445.0
Restaurants and Hotels 8138913.7 9021774.4 9712391.4 10649011.0
Total 76758539.0 81455234.0 84251489.0 87868048.0
Quarter Q4-17
Category
Fuel and Service Stations 8395288.1
General Consumer Goods 19794656.0
Restaurants and Hotels 11036473.0
Total 93091370.0
解决方案
通过找到类似的帖子,我能够弄清楚。
只需要order = pull['Quarter']
在枢轴之前添加。然后,您可以使用以下方法修复列顺序:reshape = reshape.reindex(columns=order)
推荐阅读
- c - 在调试控制台 VScode 中使用输入(stdin)
- sql - Oracle SQL,以不超过参考日期的最近日期连接表
- typescript - 为什么过滤具有未定义键的对象会在 TypeScript 严格模式下出错
- typescript - 在Typescript中按日期变量将数组元素分组为周
- python - 按索引行值与前一行值比较数据帧组
- reactjs - 我如何为我的搜索栏做后端反应?
- reactjs - 来自自定义 React Hook 和 React 组件的 NPM 包
- android - Android FCM:当应用程序在后台时,FCM 显示(通知)消息登录
- powershell - 是否可以在 Powershell 中使用 Send-PnPMail 发送附件?
- azure-web-app-service - 适用于 Visual Studio Code 的 Azure 应用服务插件看不到我的订阅