如何根据特定列中的值更改函数

时间:2019-05-19 15:26:21

标签: function group-by formula aggregate-functions

假设我有一个包含两列的表:

我现在想创建一个第三列,该列将汇总每个月的该值(并在该月一部分的每一行中显示每个月的总产品。 任何通用函数都可以做到,而无需我在函数中指定每种情况? (如果我要使用“ If”函数,那就是我要做的。)

示例: 我最初的2列是“月”和“值”,我想要一个将创建“总和”列的函数。

Month  Value     Sum
6      23        57
6      34        57
7      56        100
7      44        100
8      12        12

1 个答案:

答案 0 :(得分:0)

一般程序

一般过程是将sumgroup by 'Month'一起使用。这将返回一个表,其中 Month 用作索引(没有重复的月份),并且您有一列包含所有月份的总和。

以您的示例为例,您将获得以下中间表:

Month  Sum
6      57
7      100
8      12

然后,您可以使用此表在原始表中创建 Sum 列。
基本上,您只需从中间表中具有相同 Month 的所有行的 Sum 中复制值即可。

现在如何执行此操作取决于您所使用的技术(尚未指定),因此,我用已知的工具举几个例子:如果您使用不同的工具,请尝试适应这个想法。

使用python熊猫

假设df是用pandas创建的原始表(没有 Sum 列)。然后该过程将是:

#create the intermediate table using sum and groupby
idf = df.groupby('Month').sum()

#edit idf so that the number of rows is the same of df
idf = idf.loc[df['Month']].reset_index()

#adding the column to the original table
df['Sum'] = idf['Value']

使用MySQL

假设otableMySQL数据库中的原始表(不包括Sum列)。然后该过程将是:

#create additional column to store the Sum, null by default 
ALTER TABLE otable ADD COLUMN Sum INT;

#create the intermediate table using sum and groupby
CREATE TEMPORARY TABLE idf SELECT SUM(Value) FROM otable GROUP BY Month;

#update the original table
UPDATE otable o, idf i SET o.Sum = i.`SUM(Value)` WHERE o.Month = i.Month;

使用excel

对于excel,它已经回答了herehere