python - Pandas 虫? : Mean of an grouped-by int64 column stays as int64 in some circumstances

标签 python csv pandas

我发现一个非常奇怪的(恕我直言)行为,一些数据从 CSV 文件加载到 pandas 中。为了保护无辜者,让我们声明 DataFrame 位于变量 homes 中,并且除其他外,具有以下列:

In [143]: homes[['zipcode', 'sqft', 'price']].dtypes
Out[143]:
zipcode     int64
sqft        int64
price       int64
dtype: object

为了获得每个邮政编码的平均价格,我尝试了:

In [146]: homes.groupby('zipcode')[['price']].mean().head(n=5)
Out[146]:
           price
zipcode
28001     280804
28002     234284
28003     294111
28004    1355927
28005     810164

奇怪的是,价格平均值是一个 int64,如下所示:

In [147]: homes.groupby('zipcode')[['price']].mean().dtypes
Out[147]:
price    int64
dtype: object

我无法想象为什么某些整数的平均值没有提升为 float 的任何技术原因。更重要的是,只需添加另一列,价格就会变成 float64 正如我所期望的那样:

In [148]: homes.groupby('zipcode')[['price', 'sqft']].mean().dtypes
Out[148]:
price       float64
sqft        float64
dtype: object

                  price          sqft
zipcode
28001     280804.690608  14937.450276
28002     234284.035176   7517.633166
28003     294111.278571  10603.096429
28004    1355927.097792  13104.220820
28005     810164.880952  19928.785714

为了确保我没有遗漏一些非常明显的东西,我创建了另一个非常简单的 DataFrame (df) 但是,对于这个,这个行为没有出现:

In [161]: df[['J','K']].dtypes
Out[161]:
J    int64
K    int64
dtype: object

In [164]: df[['J','K']].head(n=10)
Out[164]:
   J   K
0  0  -9
1  0 -14
2  0   8
3  0 -11
4  0  -7
5 -1   7
6  0   2
7  0   0
8  0   5
9  0   3

In [165]: df.groupby('J')[['K']].mean()
Out[165]:
           K
J
-2 -2.333333
-1  0.466667
 0 -1.030303
 1 -1.750000
 2 -3.000000

请注意,对于单列 K:int64,按 J 分组,另一个 int64,均值直接是 float 。 homes DataFrame 是从 一个提供的 CSV 文件,df 文件是在 pandas 中创建的,写入 CSV 文件然后读回。

最后但同样重要的是,我使用的是 pandas 0.16.2。

最佳答案

正如你们中的一些人在评论中所建议的那样,这是 pandas 中的一个错误。我刚举报了here .

截至目前,它已被pandas团队接受。

谢谢

关于python - Pandas 虫? : Mean of an grouped-by int64 column stays as int64 in some circumstances,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32809182/

相关文章:

python - 使用命名(fifo)管道在 python 和 c++ 之间传输数组(图像)

python - 将快速串行数据写入文件(csv 或 txt)

python - .CSV 文件字典的数据清理

python - 从源代码(或 Heroku)中找出 Python 版本

python - 由于 pip 中的 numpy NameError,无法安装 mdfreader 版本 3

java - 如何将仅包含标题(无行)的数据集写入 hdfs 位置(csv 格式),以便在下载时包含标题?

python - 根据其他列值生成列

python - 迭代数据帧行

python - ValueError : 2 columns passed, 传递的数据有 1 列

Python Appengine 在执行 app.yaml 之前运行某些代码