为什么数据透视表返回Int64类型错误?



我试图pivot数据框,但它一直返回Int64错误。实际上没有回答一个类似的问题—是什么导致这些Int64列导致TypeError?

这是我的dataframe的类型:

#   Column        Non-Null Count  Dtype 
---  ------        --------------  ----- 
0   price         30159 non-null  Int64 
1   type          30159 non-null  object
2   size          30155 non-null  Int64 
3   location      30159 non-null  object
4   neighborhood  30159 non-null  object
dtypes: Int64(2), object(3)

透视表代码:

pfraw = pd.pivot_table(pfraw, values = 'price', index = 'neighborhood', columns = 'type')

和错误信息的最后位:

273     dtype = np.dtype(dtype)
275 if not isinstance(dtype, np.dtype):
276     # enforce our signature annotation
--> 277     raise TypeError(dtype)  # pragma: no cover
279 converted = maybe_downcast_numeric(result, dtype, do_round)
280 if converted is not result:
TypeError: Int64

我不明白为什么它会返回一个错误与Int64。

首先,让我们创建一个类似于OP的df

import pandas as pd
df = pd.DataFrame( {'price': [10, 12, 18, 10, 12], 'type': ['A', 'A', 'A', 'B', 'B'], 'size': [10, 12, 18, 10, 12], 'location': ['A', 'A', 'A', 'B', 'B'], 'neighborhood': ['A', 'A', 'A', 'B', 'B']})

如果有人打印df,他将看到这个有int64而不是Int64(与OP相反)。注意:从我的回答可以看出两种dtype的区别。

print(df.info(verbose=True))
[Out]:
#   Column        Non-Null Count  Dtype 
---  ------        --------------  ----- 
0   price         5 non-null      int64 
1   type          5 non-null      object
2   size          5 non-null      int64 
3   location      5 non-null      object
4   neighborhood  5 non-null      object

并且,使用int64,您将能够创建具有索引"邻域"、列"类型"和值"价格"的数据透视表,使用以下命令

df_pivot = df.pivot_table(index='neighborhood', columns='type', values='price')

输出

type                  A     B
neighborhood                 
A             13.333333   NaN
B                   NaN  11.0

但是,对于Int64,数据透视表可能生成错误。

为了处理这个问题,需要将类型转换为int64

df[['price', 'size']] = df[['price', 'size']].astype('int64')  

import numpy as np
df[['price', 'size']] = df[['price', 'size']].astype(np.int64)

而且,OP很可能有缺失值。处理这个问题的最快方法是删除缺少值的行。为了找到和删除缺失的值,我在这里的答案可能会有所帮助。

作为参考,这是指向模块maybe_downcast_to_dtype的直接链接,该模块正在引发OP所具有的错误。

最新更新