我在具有混合类型(数字和对象)的 DataFrame 上使用 Pandas groupby 函数。
>>> import pandas as pd
>>>
>>> d = {
... "sales": {
... "0": 3963.0,
... "1": 2312.7,
... },
... "Id": {
... "0": 10001,
... "1": 10003,
... },
... "Blah": {
... "0": "Blah1",
... "1": "Blah2",
... }
... }
>>>
>>> d=pd.DataFrame(d)
>>>
>>> print d.dtypes
Blah object
Id int64
sales float64
dtype: object
当我将一个数字函数应用于组时,例如 max() 或 mean(),我得到一个类型为 object 的 DataFrame 返回
>>> print d.groupby('Id').max()['sales']
Id
10001 3963.0
10003 2312.7
Name: sales, dtype: object
当我先只选择数字列,然后对组应用数字函数,例如 max() 或 mean(),我得到一个数字类型的 DataFrame
>>> print d[['sales','Id']].groupby('Id').max()['sales']
Id
10001 3963.0
10003 2312.7
Name: sales, dtype: float64
第二个结果是我所期望的 - 或者更确切地说,我不明白为什么将数值函数 max 或 mean 应用于非数值类型的数据框会将数值强制转换为对象。
例如,如果原始数据框中没有非数字对象类型,则不会以奇怪的方式强制转换类型:
>>> del d['Blah']
>>> d[['Id','sales']].groupby('Id').max()['sales']
Id
10001 3963.0
10003 2312.7
Name: sales, dtype: float64
>>> d.groupby('Id').max()['sales']
Id
10001 3963.0
10003 2312.7
Name: sales, dtype: float64
>>>
编辑 - 这是我的版本信息:
Mac OS X 10.9 w/ Python 2.7.6
Cython==0.19.2
matplotlib==1.3.1
numpy==1.8.0
pandas==0.13.1
scipy==0.13.0
请您参考如下方法:
不记得这是什么时候修复的,但在 master/0.14(即将推出)中是正确的。
In [48]: d
Out[48]:
Blah Id sales
0 Blah1 10001 3963.0
1 Blah2 10003 2312.7
[2 rows x 3 columns]
In [49]: d.dtypes
Out[49]:
Blah object
Id int64
sales float64
dtype: object
In [50]: d.groupby('Id').max()['sales']
Out[50]:
Id
10001 3963.0
10003 2312.7
Name: sales, dtype: float64
