【问题标题】:Pandas Groupby of categorical features takes too much RAM and time分类特征的 Pandas Groupby 占用太多 RAM 和时间
【发布时间】:2020-03-16 17:01:55
【问题描述】:

我试图理解为什么 panda 的分类特征的 groupby 占用太多 RAM,因此需要太多时间来执行。 考虑以下数据框:

import pandas as pd
from numpy.random import randint, randn
from pandas.api.types import CategoricalDtype

df = pd.DataFrame({'cat_1':randint(0,60,300000),
  'cat_2':randint(0,40,300000),
  'cat_3':randint(0,70,300000),
  'cat_4':randint(0,30,300000),
  'value':randn(300000)})

所有的cat_1, ..., cat_4 都是 int64 并且列 value 是浮点数。我可以使用 groupby 命令轻松计算列 value 的平均值,如下所示:

df.groupby(['cat_1', 'cat_2', 'cat_3', 'cat_4']).agg({'value':'mean'}).reset_index()

不到一秒钟就可以得到这个结果:

如果我现在将 int64 列转换为类别,然后重复以下相同的计算:

for col in ['cat_1', 'cat_2', 'cat_3', 'cat_4']:
    df[col] = df[col].astype('category')

df.groupby(['cat_1', 'cat_2', 'cat_3', 'cat_4']).agg({'value':'mean'}).reset_index()

我会得到错误的结果(以 NAN 作为平均值的行太多)

我使用 pandas==0.25.3 和 Python 3.7.4。

谁能帮我处理这个案子?

【问题讨论】:

    标签: python-3.x pandas pandas-groupby


    【解决方案1】:

    observed=True试试groupby:

    print(df.groupby(['cat_1', 'cat_2', 'cat_3', 'cat_4'], observed=True).agg({'value':'mean'}).reset_index())
    

    输出

           cat_1 cat_2 cat_3 cat_4     value
    0         33    32    46     6 -2.890154
    1         33    32    46    27 -2.476471
    2         33    32    46    13  0.500962
    3         33    32    46    22  1.833252
    4         33    32    40    12  0.666898
    ...      ...   ...   ...   ...       ...
    291135    52     9     9    18 -0.382408
    291136    52     9     9    19 -1.325040
    291137    52     9    27     2 -0.025054
    291138    52     9    38    23  0.652825
    291139    52     9    38     7 -1.949213
    
    [291140 rows x 5 columns]
    

    来自documentation

    观察到:bool,默认为 False

    这仅适用于任何 groupers 是分类的。如果为真:仅显示分类分组的观察值。如果为假: 显示分类分组的所有值。

    0.23.0 版中的新功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 2019-05-25
      • 2018-01-13
      • 2019-08-18
      相关资源
      最近更新 更多