Pandas 中数据透视表的语法是什么?文档好像不对?

What is the syntax for pivot tables in Pandas? Docs don't seem to be right?

我可能完全疯了,但我正在阅读 the docs for pivot_table in Pandas, and even some guides

直接使用文档中的示例和我自己的数据:

import pandas as pd

df = pd.read_csv('data.csv')
pivot_table(df, values='D', index=['A', 'B'], columns=['C'], aggfunc=np.sum)

产生错误:

pivot_table(df, values='D', index=['A', 'B'], columns=['C'], aggfunc=np.sum) NameError: name 'pivot_table' is not defined

我做错了什么?我需要额外导入吗?

pivot_table 是顶级函数,因此您需要使用 pd.pivot_table.

对其进行限定

文档中的代码假定您已完成以下操作:

from pandas import *

这就是混乱的根源。

所以从文档中的示例:

In [41]:
t="""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"""
df = pd.read_csv(io.StringIO(t), sep='\s+')
<class 'pandas.core.frame.DataFrame'>
Int64Index: 9 entries, 0 to 8
Data columns (total 4 columns):
A    9 non-null object
B    9 non-null object
C    9 non-null object
D    9 non-null int64
dtypes: int64(1), object(3)
memory usage: 360.0+ bytes

以下会产生错误

In [42]:
pivot_table(df, values='D', index=['A', 'B'], columns=['C'], aggfunc=np.sum)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-42-98a5be0e193b> in <module>()
----> 1 pivot_table(df, values='D', index=['A', 'B'], columns=['C'], aggfunc=np.sum)

NameError: name 'pivot_table' is not defined

虽然以下工作:

In [43]:
pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'], aggfunc=np.sum)

Out[43]:
C        large  small
A   B                
bar one      4      5
    two      7      6
foo one      4      1
    two    NaN      6

就像这样:

In [44]:
from pandas import *
pivot_table(df, values='D', index=['A', 'B'], columns=['C'], aggfunc=np.sum)

Out[44]:
C        large  small
A   B                
bar one      4      5
    two      7      6
foo one      4      1
    two    NaN      6

只需在代码开头添加以下几行,

import pandas as pd 
from pandas import * 

原因是 pivot_table 是顶级函数,要使用它,我们需要从 pandas 导入所有函数。

从技术上讲,我们现在不会讨论什么是顶级函数:) 我把它留给你去探索:)