首页 > 解决方案 > 将数据透视表存储到 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 的任何建议?

标签: pythonpandascsvpivot-table

解决方案


推荐阅读