【问题标题】:Group by with aggregation function as new field in pandas具有聚合功能的分组作为熊猫中的新字段
【发布时间】:2017-07-01 12:42:28
【问题描述】:

如果我在 mysql 表上进行以下分组

SELECT col1, count(col2) * count(distinct(col3)) as agg_col
FROM my_table
GROUP BY col1

我得到的是一个三列的表格

col1 col2 agg_col

我怎样才能在 pandas 数据框上做同样的事情?

假设我有一个包含三列 col1 col2 和 col3 的 Dataframe。按操作分组

grouped = my_df.groupby('col1')

将返回按 col1 分组的数据

还有

agg_col_series = grouped.col2.size() * grouped.col3.nunique()

将返回与 sql 查询中的聚合列等效的聚合列。但是如何在分组数据框中添加它?

【问题讨论】:

标签: python mysql pandas


【解决方案1】:

我们需要查看您的数据以确定,但我认为您需要简单地重置您的 agg_col_series 的索引:

agg_col_series.reset_index(name='agg_col')

带有虚拟数据的完整示例:

import random
import pandas as pd

col1 = [random.randint(1,5) for x in range(1,1000)]
col2 = [random.randint(1,100) for x in range(1,1000)]
col3 = [random.randint(1,100) for x in range(1,1000)]

df = pd.DataFrame(data={
        'col1': col1,
        'col2': col2,
        'col3': col3,
    })

grouped = df.groupby('col1')
agg_col_series = grouped.col2.size() * grouped.col3.nunique()

print agg_col_series.reset_index(name='agg_col')

index   col1  agg_col
0       1    15566
1       2    20056
2       3    17313
3       4    17304
4       5    16380

【讨论】:

  • 谢谢尼克!!
【解决方案2】:

让我们将groupby 与使用sizenunique 的lambda 函数一起使用 然后 rename 将系列转到 'agg_col' 和 reset_index 以获取数据帧。

import pandas as pd
import numpy as np

np.random.seed(443)
df = pd.DataFrame({'Col1':np.random.choice(['A','B','C'],50),
                   'Col2':np.random.randint(1000,9999,50),
                   'Col3':np.random.choice(['A','B','C','D','E','F','G','H','I','J'],50)})

df_out = df.groupby('Col1').apply(lambda x: x.Col2.size * x.Col3.nunique()).rename('agg_col').reset_index()

输出:

  Col1  agg_col
0    A      120
1    B       96
2    C      190

【讨论】:

  • 感谢你们俩。我选择@nick-braunagel 答案的唯一原因是因为他排在第一位,而且为了提高声誉,他的声誉较低:)
  • @apostolos。伟大的!很高兴它对你有效。感谢您的支持。
猜你喜欢
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 2017-01-14
  • 2019-06-13
  • 1970-01-01
  • 1970-01-01
  • 2013-05-09
  • 2019-02-01
相关资源
最近更新 更多