需要在 pandas 中的数据帧上聚合计数(rowid,colid)

Need to aggregate count(rowid, colid) on dataframe in pandas

我一直在努力把这个

| row_id | col_id |
|--------|--------|
|   1    |   23   |
|   4    |   45   |
|  ...   |  ...   |
|   1    |   23   |
|  ...   |  ...   |
|   4    |   45   |
|  ...   |  ...   |
|   4    |   45   |
|  ...   |  ...   |

进入这个

| row_id | col_id |  count  |
|--------|--------|---------|
|   1    |   23   |    2    |
|   4    |   45   |    3    |
|  ...   |  ...   |   ...   |

因此所有 (row_i, col_j) 次出现都添加到 'count' 列中。请注意,row_id 和 column_id 在这两种情况下都不是唯一的。

现在成功到现在,至少如果我想保持高效的话。我可以遍历每一对并将出现的次数加起来,但是 pandas 中必须有一种更简单的方法——或者 numpy 就此而言。

谢谢!

编辑 1:

正如@j-bradley 所建议的,我尝试了以下方法

# I use django-pandas
rdf = Record.objects.to_dataframe(['row_id', 'column_id'])
_ = rdf.groupby(['row_id', 'column_id'])['row_id'].count().head(20)
_.head(10)

然后输出

    row_id  column_id
1       108          1
        168          1
        218          1
        398          2
        422          1
10      35           2
        355          1
        489          1
100     352          1
        366          1
Name: row_id, dtype: int64

这似乎还可以。但它是一个 Series 对象,我不确定如何将其转换为具有所需三列的数据框。 Pandas 菜鸟,看起来。有什么建议吗?

再次感谢。

您可以按 a 和 b 列分组,然后按对象调用 count

df =pd.DataFrame({'A':[1,4,1,4,4], 'B':[23,45,23,45,45]})
df.groupby(['A','B'])['A'].count()

returns:

A  B 
1  23    2
4  45    3

编辑以使答案更明确

要将 series 变回具有名为 count 的列的 dataframe

_ = df.groupby(['A','B'])['A'].count()

系列名称成为栏目名称:

_.name = 'Count'

重置索引,将多索引提升为列并将系列转换为数据框:

df =_.reset_index()