Python笔记:Pandas透视表(pivot_table),简单调参即可实现丰富的功能

中文原文:https://blog.csdn.net/chencheng126/article/details/50119215

英文原文:https://pbpython.com/pandas-pivot-table-explained.html  从这里可以下载excel数据文件。

# -*- coding: utf-8 -*-
"""
Created on Fri Jun  7 14:04:21 2019

@author: User
"""

import pandas as pd
import numpy as np

df=pd.read_excel('data\\sales-funnel.xlsx')
print(df.head())
print(df.info())

df['Status']=df['Status'].astype('category')
df['Status'].cat.set_categories(["won","pending","presented","declined"],inplace=True)
#print(df.head())

table=pd.pivot_table(df,
               index=['Status','Manager'],
               columns=['Product'],
               values=['Price','Quantity'],
               fill_value=0,
               aggfunc={'Quantity':len,'Price':sum},
               margins=True)

print(table)

table.to_excel('data\out_pivot0607.xlsx')
print("\n 查询 Manager:")
#print(table.query('Manager == ["Debra Henley"]'))
print(table.query('Status == ["won","declined"]'))

运行:

Python笔记:Pandas透视表(pivot_table),简单调参即可实现丰富的功能_第1张图片

你可能感兴趣的:(python学习)