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

How do I change a function according to a value in a specific column

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

  1. 月份
  2. 价值

我现在想创建一个第 3 列,它将汇总每个月的值(并将在本月的每一行中显示每个月的总产品。 任何通用函数都可以做到这一点而无需我在函数中指定每个案例? (如果我要使用 "If" 函数,那就是我会做的......)

给出的例子: 我最初的 2 列是 "Month" 和 "Value",我想要一个函数来创建 "Sum" comlumn。

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

一般程序

一般程序是使用 sumgroup by 'Month'。这将 return a table 其中 Month 用作索引(没有重复的月份)并且您有一个包含所有月份总和的列。

使用你的例子,你会得到以下中间体table:

Month  Sum
6      57
7      100
8      12

然后您可以使用此 table 在原始 table.
中创建 Sum 列 基本上,您只需从具有相同 Month.

的所有行中的中间值 table 复制 Sum 中的值

现在如何做到这一点取决于你使用的技术,你没有指定,所以我用我知道的工具做了几个例子:如果你使用不同的工具,试着适应这个想法。

使用 python pandas

假设 df 是您使用 pandas 创建的原始 table(没有 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

假设 otable 是您在 MySQL 数据库中的原始 table(没有 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 已经回答 here and here