Skip to main content
 首页 » 编程设计

python之Pandas 中的数据透视表之不可排序的类型

2025年05月04日998°冷暖

我有一个 pandas 数据框 (df),基本上如下所示

    TestDate            Manager     Score 
0   2015-06-05 00:00:00 Jane Smith  5.000000 
1   2015-06-05 00:00:00 John Doe    4.875000 
2   2015-06-05 00:00:00 Jane Doe    4.428571 
3   2015-06-05 00:00:00 John Doe    4.000000 
4   2015-06-07 00:00:00 Josh Smith  3.500000 
.....(~250 rows) 
 
df.dtypes() 
TestDate                 datetime64[ns] 
Manager                  object 
Score                    float64 
dtype: object 

我只想在此基础上创建一个简单的数据透视表来计算每位经理每天的平均分。因此,我应该为每个经理的名字留一列。

但是,当我运行的时候

df.pivot('TestDate', 'Manager', 'Score') 

我明白了

TypeError: unorderable types: int() <= NoneType() 

输出

<class 'pandas.core.frame.DataFrame'> 
DatetimeIndex: 11 entries, 2015-06-05 00:00:00 to 2015-06-24 00:00:00 
Data columns (total 11 columns): 
John Doe           4  non-null values 
Jane Doe           4  non-null values 
.... 
dtypes: float64(11) 

为什么我会收到这种类型错误?它应该是使用均值作为浮点字段上的自动聚合函数的字符串字段的简单枢轴?

请您参考如下方法:

你可以试试 pivot_table

df.pivot_table(values='Score', index='TestDate', columns='Manager', aggfunc='mean')