python - 在 Pandas GroupBy 中计算和连接整数

标签 python pandas concatenation pandas-groupby

假设这是我的 df

   A   B   C
0  a  33  13
1  b  44  14
2  a  55  15
3  a  66  16
4  b  77  17
5  c  88  18

我试着得到这样的东西

   A      B         B     C
      count      list   sum
0  a      3  33,55,66    44
1  b      2     44,77    31
2  c      1        88    81

有什么pythonic的方法可以做到吗?

这是我的代码,但不是pythonic

df.groupby('A').agg({'B': ["count", lambda x: ','.join(x.astype(str))], 'C':sum})

最佳答案

您可以将字典传递给 agg:

In [11]: df.groupby("A").agg({"B": ["count", list], "C": ["sum"]})
Out[11]:
      B                 C
  count          list sum
A
a     3  [33, 55, 66]  44
b     2      [44, 77]  31
c     1          [88]  18

要添加逗号,我会使用一个函数:

In [21]: def list_(ls):
    ...:     return ",".join(map(str, ls))
    ...:

In [22]: list_.__name__ = "list"

In [23]: df.groupby("A").agg({"B": ["count", list_], "C": ["sum"]})
Out[23]:
      B             C
  count      list sum
A
a     3  33,55,66  44
b     2     44,77  31
c     1        88  18

关于python - 在 Pandas GroupBy 中计算和连接整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55331252/

相关文章:

python - 热图的正确顺序的数据透视表

python - 使用python的图形工具计算最短路径和距离的有效方法

python - pandas.DataFrame.load/python2 和 python3 之间的保存 : pickle protocol issues

pandas - 在 Pandas 中聚合多列时如何重置索引

python - 这对 Monty Hall 来说是好还是坏 'simulation'?怎么来的?

python - django-cms 中的 create_user.py 问题

python - 无法安装最新版本的 pandas (1.0.3)

Python xarray.concat 然后 xarray.to_netcdf 生成巨大的新文件大小

mysql - 在 MySQL 中选择连接子字符串并替换

在线性时间内用 crt 连接 C 字符串