【问题标题】:pandas groupby numeric functions coerce numeric to object when DataFrame contains object当 DataFrame 包含对象时,pandas groupby 数字函数将数字强制转换为对象
【发布时间】: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

这第二个结果是我所期望的 - 或者我不明白为什么将数字函数 maxmean 应用于具有非数字类型的数据帧会强制将数值转换为对象。

例如,如果原始数据框中没有非数字对象类型,则不会以奇怪的方式强制类型:

>>> 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 看起来很相似。)
  • 我想知道这是否是一个错误 - 或者如果不是,为什么它会这样工作。我认为这是一个错误,因为毫无戒心的用户可能希望类型受到尊重并被抓住......

标签: python pandas


【解决方案1】:

不记得确切的修复时间,但在 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

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 2021-06-24
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多