在Python中复制dcast

0 投票
1 回答
1036 浏览
提问于 2025-04-18 15:23

我有一个很大的 pandas 数据框,内容大致如下:

col1     col2     col3    col4
 a        d        sd       2
 b        sd       sd       2
 a        ds       hg       3
 a        ew       rt       3
 b        ss       qq       4

我想要的输出结果类似于下面这个:

col1     sum
a        8
b        6

这里的 'sum' 列是 col4 列中所有值的总和,针对 col1 列中的每个唯一值。 在 R 语言中,可以使用 dcast 来实现这个功能。

dcast(dataframe, col1 ~ count, sum, value.var = 'col4')

那我该如何在 Python 中做到这一点呢?

1 个回答

2

我觉得你想要的内容可以在分组:分割-应用-合并中找到:

groups = df.groupby('col1')
splitgroups = groups['col4']
sums = splitgroups.aggregate(np.sum)

或者,更直接一点:

sums = df.groupby('col1').aggregate({'col4': np.sum})

不过建议你还是把整个页面都读一遍;Pandas的groupby功能比R的dcast更灵活(它的设计目的是为了实现SQL聚合、Excel透视表等功能),这也意味着你的想法可能在这两者之间不一定能完全对应。

下面是它的实际应用:

>>> # your DataFrame, with a default index
>>> df = pd.DataFrame({'col1': 'a b a a b'.split(), 'col2': 'd sd ds ew ss'.split(), 'col3': 'sd sd hg rt qq'.split(), 'col4': (2, 2, 3, 3, 4)})
>>> sums = df.groupby('col1').aggregate({'col4': np.sum})
>>> sums
      col4
col1
a        8
b        6

撰写回答