Dou*_*ith 3 python pivot-table pandas
我可能完全疯了,但我正在阅读Pandas的文档pivot_table,甚至一些指南
从字面上使用文档中的示例和我自己的数据:
import pandas as pd
df = pd.read_csv('data.csv')
pivot_table(df, values='D', index=['A', 'B'], columns=['C'], aggfunc=np.sum)
Run Code Online (Sandbox Code Playgroud)
产生错误:
ivot_table(df,values='D',index=['A','B'],columns=['C'],aggfunc=np.sum)NameError:名称'pivot_table'未定义
我究竟做错了什么?我需要额外导入吗?
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
Run Code Online (Sandbox Code Playgroud)
以下产生错误
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
Run Code Online (Sandbox Code Playgroud)
虽然以下作品有效:
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
Run Code Online (Sandbox Code Playgroud)
就像这样:
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
Run Code Online (Sandbox Code Playgroud)