Ami*_*ory 6 python group-by pivot-table pandas
(请注意,Pandas有一个问题:group by和Pivot表差异,但这个问题不同.)
假设您从DataFrame开始
df = pd.DataFrame({'a': ['x'] * 2 + ['y'] * 2, 'b': [0, 1, 0, 1], 'val': range(4)})
>>> df
Out[18]:
a b val
0 x 0 0
1 x 1 1
2 y 0 2
3 y 1 3
Run Code Online (Sandbox Code Playgroud)
现在假设您要创建索引a,列b,单元格中的值val,并指定在结果单元格中有两个或更多值时要执行的操作:
b 0 1
a
x 0 1
y 2 3
Run Code Online (Sandbox Code Playgroud)
然后你可以通过
df.val.groupby([df.a, df.b]).sum().unstack()
Run Code Online (Sandbox Code Playgroud)
或通过
pd.pivot_table(df, index='a', columns='b', values='val', aggfunc='sum')
Run Code Online (Sandbox Code Playgroud)
所以在我看来,两者之间的对应关系之间有一个简单的对应关系(给定一个,你几乎可以写一个脚本来将它转换成另一个).我还想到了更复杂的层次索引/列的情况,但我仍然认为没有区别.
有没有我错过的东西?
是否可以使用one而不是其他操作执行操作?
也许,操作更容易使用一个而不是另一个?
如果没有,为什么不弃用pivot_tale?groupby似乎更普遍.
如果我pivot_table(index, columns, values, aggfunc)正确理解了源代码,则将其等效于:
df.groupby([index + columns]).agg(aggfunc).unstack(columns)
Run Code Online (Sandbox Code Playgroud)
加:
pivot_table() 还会从列轴上删除多余的多级(请参见下面的示例)dropna参数:不包括所有条目均为NaN的列演示:(我从文档字符串[ pivot_table()]的源代码中获得了这个DF )
In [40]: df
Out[40]:
A B C D
0 foo one small 1
1 foo one large 2
2 foo one large 2
3 foo two small 3
4 foo two small 3
5 bar one large 4
6 bar one small 5
7 bar two small 6
8 bar two large 7
In [41]: df.pivot_table(index=['A','B'], columns='C', values='D', aggfunc=[np.sum,np.mean])
Out[41]:
sum mean
C large small large small
A B
bar one 4.0 5.0 4.0 5.0
two 7.0 6.0 7.0 6.0
foo one 4.0 1.0 2.0 1.0
two NaN 6.0 NaN 3.0
Run Code Online (Sandbox Code Playgroud)
在顶层列注意: D
In [42]: df.groupby(['A','B','C']).agg([np.sum, np.mean]).unstack('C')
Out[42]:
D
sum mean
C large small large small
A B
bar one 4.0 5.0 4.0 5.0
two 7.0 6.0 7.0 6.0
foo one 4.0 1.0 2.0 1.0
two NaN 6.0 NaN 3.0
Run Code Online (Sandbox Code Playgroud)
为什么不弃用ivot_tale?groupby似乎更为通用。
IMO,因为它非常容易使用和方便!;)