pandas里的pivot和pivot_table是啥关系

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 的本质,根据给定的 indexcolumns 返回变形后的 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_indexunstack 复现。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值