【问题标题】:What causes these Int64 columns to cause a TypeError?是什么导致这些 Int64 列导致 TypeError?
【发布时间】:2021-07-24 00:15:19
【问题描述】:

我有一个带有多个 Int64 类型的标志/虚拟变量的 pandas DataFrame。

我正在汇总其他字段并取平均值以计算百分比。

df.groupby(["key1", "key2"]).mean()

当我尝试取平均值时,我得到TypeError: cannot safely cast non-equivalent float64 to int64.

当我尝试逐一取每一列的平均值时,我没有收到错误。

我正在尝试了解可能导致错误的原因。任何见解将不胜感激。

这里是对数据的描述:

In:

df.info()

Out:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 6910491 entries, 82222 to 6858085
Data columns (total 5 columns):
 #   Column     Dtype 
---  ------     ----- 
 0   key1       object
 1   key2       object
 2   cond1      int64 
 3   cond2      Int64 
 4   cond1and2  Int64 
dtypes: Int64(2), int64(1), object(2)
memory usage: 329.5+ MB

In:

df.describe()

Out:


    cond1   cond2   cond1and2
count   6.910491e+06    6.910491e+06    6.910491e+06
mean    2.004735e-02    1.050030e-01    6.695038e-03
std 1.401622e-01    3.065573e-01    8.154885e-02
min 0.000000e+00    0.000000e+00    0.000000e+00
25% 0.000000e+00    0.000000e+00    0.000000e+00
50% 0.000000e+00    0.000000e+00    0.000000e+00
75% 0.000000e+00    0.000000e+00    0.000000e+00
max 1.000000e+00    1.000000e+00    1.000000e+00

In: 

[print(df[c].value_counts(), "\n\n") for c in df]

Out:

c    2220221
d    2208322
b    2195117
a     286831
Name: key1, dtype: int64 


1    1925173
4    1680848
3    1656101
2    1648369
Name: key2, dtype: int64 


0    6771954
1     138537
Name: cond1, dtype: int64 


0    6184869
1     725622
Name: cond2, dtype: Int64 


0    6864225
1      46266
Name: cond1and2, dtype: Int64 


[None, None, None, None, None]

In: 

df.groupby(['key1', 'key2']).mean()

Out:

TypeError                                 Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\arrays\integer.py in safe_cast(values, dtype, copy)
    143     try:
--> 144         return values.astype(dtype, casting="safe", copy=copy)
    145     except TypeError:

TypeError: Cannot cast array from dtype('float64') to dtype('int64') according to the rule 'safe'

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-70-5cec730bfc37> in <module>
----> 1 df.groupby(['key1', 'key2']).mean()

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\groupby\groupby.py in mean(self, *args, **kwargs)
   1230         nv.validate_groupby_func("mean", args, kwargs, ["numeric_only"])
   1231         return self._cython_agg_general(
-> 1232             "mean", alt=lambda x, axis: Series(x).mean(**kwargs), **kwargs
   1233         )
   1234 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\groupby\generic.py in _cython_agg_general(self, how, alt, numeric_only, min_count)
   1002     ) -> DataFrame:
   1003         agg_blocks, agg_items = self._cython_agg_blocks(
-> 1004             how, alt=alt, numeric_only=numeric_only, min_count=min_count
   1005         )
   1006         return self._wrap_agged_blocks(agg_blocks, items=agg_items)

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\groupby\generic.py in _cython_agg_blocks(self, how, alt, numeric_only, min_count)
   1091                         # Cast back if feasible
   1092                         result = type(block.values)._from_sequence(
-> 1093                             result.ravel(), dtype=block.values.dtype
   1094                         )
   1095                     except ValueError:

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\arrays\integer.py in _from_sequence(cls, scalars, dtype, copy)
    348     @classmethod
    349     def _from_sequence(cls, scalars, dtype=None, copy=False):
--> 350         return integer_array(scalars, dtype=dtype, copy=copy)
    351 
    352     @classmethod

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\arrays\integer.py in integer_array(values, dtype, copy)
    129     TypeError if incompatible types
    130     """
--> 131     values, mask = coerce_to_array(values, dtype=dtype, copy=copy)
    132     return IntegerArray(values, mask)
    133 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\arrays\integer.py in coerce_to_array(values, dtype, mask, copy)
    245         values = safe_cast(values, dtype, copy=False)
    246     else:
--> 247         values = safe_cast(values, dtype, copy=False)
    248 
    249     return values, mask

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\arrays\integer.py in safe_cast(values, dtype, copy)
    150 
    151         raise TypeError(
--> 152             f"cannot safely cast non-equivalent {values.dtype} to {np.dtype(dtype)}"
    153         )
    154 

TypeError: cannot safely cast non-equivalent float64 to int64

【问题讨论】:

  • 我会看看我是否可以,但我不确定我是否知道如何在不暴露数据的情况下做到这一点。我在项目的另一部分做的几乎相同,它不会出错。
  • 您无需向我们展示您工作所需的数据。您只需要向我们展示一个 数据集(理想情况下是一个小型 数据集),它展示了问题。如果您无法诊断导致问题的数据是什么,那么,我们几乎没有比这更好的位置了。
  • 我添加了有关数据的更多信息。有帮助吗?
  • 我刚刚注意到我的一个字段是 int64 类型而不是 Int64 类型,但我不明白为什么当我一一处理列时它会成功。

标签: python pandas pandas-groupby typeerror


【解决方案1】:

可能是您在初始数据帧中有 Nan 值(被视为浮点数),因此出现错误消息。

试试这个:

df = df.fillna(0)  # replace Nan values with 0
df.groupby(["key1", "key2"]).mean()

【讨论】:

  • 我为上面的每个字段提供了值计数的输出。
【解决方案2】:

您可以更改所选列的数据类型,例如:

排除object 类型,然后根据需要更改类型:

# This line will give you numeric type list

lst = list(df.select_dtypes(exclude= 'object').columns) 
df[lst] = df[lst].astype('int64')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2011-02-12
    • 2011-11-27
    • 2015-09-08
    相关资源
    最近更新 更多