pandas里的pivot和pivot_table是啥关系
pivot
首先函数定义如下:
DataFrame.pivot(index=None, columns=None, values=None)
Return reshaped DataFrame organized by given index / column values.
Reshape data (produce a “pivot” table) based on column values. Uses unique values from specified index / columns to form axes of the resulting DataFrame. This function does not support data aggregation, multiple values will result in a MultiIndex in the columns.
划重点 reshaped
,这就是 pivot
的本质,根据给定的 index
和 columns
返回变形后的 DataFrame
, 具体看下面例子:
from collections import OrderedDict
from pandas import DataFrame
import pandas as pd
import numpy as np
table = OrderedDict((
("Item", ['Item0', 'Item0', 'Item1', 'Item1']),
('CType',['Gold', 'Bronze', 'Gold', 'Silver']),
('USD', ['1$', '2$', '3$', '4$']),
('EU', ['1€', '2€', '3€', '4€'])
))
d = DataFrame(table)
p = d.pivot(index='Item', columns='CType', values='USD')
可以看到,只是对原数据做了一个简单的变形操作,但如果我们修改一下原数据,可能会出现下面的问题:
可以看到通过给定的索引和列,我们在同一个位置得到了两个值,这时候调用 pivot
就会报错,所以调用这个函数之前我们需要确定对于指定的行和列没有重复值。
pivot_table
而 pivot_table
就是来解决这个问题,对于同样的情况,它的表现如何
table = OrderedDict((
("Item", ['Item0', 'Item0', 'Item0', 'Item1']),
('CType',['Gold', 'Bronze', 'Gold', 'Silver']),
('USD', [1, 2, 3, 4]),
('EU', [1.1, 2.2, 3.3, 4.4])
))
d = DataFrame(table)
p = d.pivot_table(index='Item', columns='CType', values='USD')
可以看到对于重复值, pivot_table
通过聚合函数 np.mean
进行了聚合,对于不同的需求,我们传入不同的聚合函数。
总结
pivot
函数的本质是变形,可以通过 set_index
和 unstack
复现。
而 pivot_table
函数的本质在于重塑和聚合,可以通过 groupby
复现。
参考
https://nikgrozev.com/2015/07/01/reshaping-in-pandas-pivot-pivot-table-stack-and-unstack-explained-with-pictures/
https://blog.csdn.net/gdkyxy2013/article/details/85228782