python - 将数据透视表存储到 csv - 保留所有数据
问题描述
在尝试将pivot_table的结果存储到 csv 时,它不会保留所有数据(标题)
这是示例代码:
data = [{'TestPriority': 3, 'AutomationStatus': 'Done'},
{'TestPriority': 4, 'AutomationStatus': 'Review'}, {'TestPriority': 2,
'AutomationStatus': 'Review for Automation'}, {'TestPriority': 2,
'AutomationStatus': 'Review for Automation'}]
df = pd.DataFrame(data)
df['AutomationStatus'] = np.where(
df['AutomationStatus'] == 'Done', 'Automated', 'Manual')
res = df.pivot_table(
index='AutomationStatus', columns=['TestPriority'],
aggfunc=len, fill_value=0)
print(res)
res.to_csv('sample.csv', sep=',')
print 语句的结果如下:
TestPriority 2 3 4
AutomationStatus
Automated 0 1 0
Manual 2 0 1
虽然生成的 csv 不显示TestPriority
标题:
AutomationStatus,2,3,4
Automated,0,1,0
Manual,2,0,1
关于如何在不丢失数据的情况下将 pivot_table 的结果正确存储到 csv 的任何建议?
解决方案
推荐阅读
- java - 如何从同一个 Java 项目的 jar 文件中运行 ant 命令?
- haskell - 使用任一时如何对条件进行排序
- node.js - AWS Elasticsearch 和 Cognito - 如何允许 Cognito 用户创建私有索引?
- vue.js - 使用 Nuxt 为 css-loader 扩展 Webpack 的问题
- algorithm - 为什么第一个决策有更好的覆盖测试用例?
- testing - 使用 Intellij 运行测试时“未收到测试事件”
- react-native - 开玩笑未能测试导入 FontAwesomeIcon 的组件
- c# - 如何在 ASP.NET Core 3 的 Blazor 页面中正确重用具有授权的控制器
- ruby-on-rails - Rails activerecord 在 HABTM 关联中查询错误的列名
- reactjs - React Hooks and Enzyme:React 一直告诉我将状态更新包装在 act(...) 中,即使我认为我做到了