[英]Pandas Bug?: Mean of an grouped-by int64 column stays as int64 in some circumstances
我發現一個非常奇怪的(恕我直言)行為,一些數據從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
我無法想象任何技術上的原因,為什么一些整數的平均值不會被提升為浮動。 更重要的是,只需添加另一列,就可以使價格成為一個浮動64,正如我預期的那樣:
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,平均值直接是浮點數。 從提供的CSV文件中讀取了homes
DataFrame
,其中df
已在pandas中創建,寫入CSV然后回讀。
最后但並非最不重要的是,我使用的是熊貓0.16.2。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.