【发布时间】:2014-05-01 06:05:20
【问题描述】:
我在具有混合类型(数字和对象)的 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
【问题讨论】:
-
您的问题是为什么它会以这种方式工作,还是会给您带来特定的问题? (我不知道为什么它会起作用,尽管有 an old bug 看起来很相似。)
-
我想知道这是否是一个错误 - 或者如果不是,为什么它会这样工作。我认为这是一个错误,因为毫无戒心的用户可能希望类型受到尊重并被抓住......