按多列分组

1 投票
1 回答
595 浏览
提问于 2025-04-29 09:49

我有一个数据表,想要根据'VALUE'这一列中的共同条目,把20个不同的列里的数值加起来。

下面是我如何对一列进行求和的:

df.groupby('VALUE').aggregate({'COUNT':numpy.sum},as_index=False)

有没有更好的方法可以扩展到20列,而不需要一个个写出它们的名字?也就是说,我希望能有一种方法,只需要传入一个列名的列表就可以了。

请看hernamesbarbara的回答,下面有一个例子可以用来说明这个问题。

暂无标签

1 个回答

3

你可以通过在pandas的分组中使用列名列表来选择要相加的列。这样做是不是你想要的呢?

import numpy as np
import pandas as pd

data = {
    "dim1":  [np.random.choice(['foo', 'bar']) for _ in range(10)],
    "measure1":  np.random.random_integers(0, 100, 10),
    "measure2":  np.random.random_integers(0, 100, 10)
}

df = pd.DataFrame(data)
df

Out[1]:
  dim1  measure1  measure2
0  bar         9        86
1  bar        24        64
2  bar        47        46
3  foo        60        98
4  bar        94        53
5  foo        95        89
6  foo        98         9
7  bar         4        95
8  foo        63        66
9  foo        40        47

df.groupby(['dim1'])['measure1', 'measure2'].sum()

Out[2]:
      measure1  measure2
dim1
bar        178       344
foo        356       309

更新于2015-01-02 对下面评论的回复有点晚,但迟到总比不来好

如果你不知道自己有多少列,但知道列的命名规则,可以动态构建一个要汇总的列列表。这里有一种方法:

colnames = ["measure".format(i+1) for i in range(100)]  # make 100 fake columns

df = pd.DataFrame(np.ones((10, 100)), columns=colnames)
df['dim1'] = [np.random.choice(['foo', 'bar']) for _ in range(10)]   # add fake dimension to groupby

desired_columns = [col for col in df.columns if "94" in col or "95" in col]   # select columns 94 and 95

df.groupby(['dim1'])[desired_columns].sum()

Out[52]:
      measure94  measure95
dim1
bar           4          4
foo           6          6

撰写回答