Pandas:如何根据索引或groupID计算新列?

Mar*_*wer 4 indexing calculated-columns pandas

这可能是一个非常简单的问题,但我找不到解决方案:我想添加一个新列“col_new”,其操作取决于组变量(如 groupID 或日期)。因此,根据 groupID,计算应该改变。
例子:

   Year  col1  col2
0  2019    10     1
1  2019     4     2
2  2019    25     1
3  2018     3     1
4  2017    56     2
5  2017     3     2
Run Code Online (Sandbox Code Playgroud)


- for Year = 2017: col_new = col1-col2
- for Year = 2018: col_new = col1+col2
- for Year = 2019: col_new = col1*col2
另外我想将其包装在 for 循环中。

year = [2017, 2018, 2019]
for x in year:
    df["new_col]" = ................
Run Code Online (Sandbox Code Playgroud)
  • 尝试使用 if-functions <== 总是需要 else 所以它改变了前一个迭代的所有值
  • 使用 .loc 可以工作,但在长而复杂的条件下变得很难处理
  • 尝试为“年份”列设置索引。这很容易做,但后来我陷入困境。
import pandas as pd
import numpy as np

d = {'Year': [2019, 2019, 2019, 2018, 2017, 2017],
     'col1': [10, 4, 25, 3, 56, 3],
     'col2': [1, 2, 1, 1, 2, 2]}
df = pd.DataFrame(data=d) #the example dataframe
df = df.set_index("Year")
print(df)
Run Code Online (Sandbox Code Playgroud)
      col1  col2
Year            
2019    10     1
2019     4     2
2019    25     1
2018     3     1
2017    56     2
2017     3     2
Run Code Online (Sandbox Code Playgroud)

现在我需要类似的东西:
- 如果 2017 那么 col1+col2
- 如果 2018 那么 col1-col2
- 如果 2019 那么 col1*col2

piR*_*red 5

dict运营商数量

from operator import sub, add, mul

op = {2019: mul, 2018: add, 2017: sub}

df.assign(new_col=[op[t.Year](t.col1, t.col2) for t in df.itertuples()])

   Year  col1  col2  new_col
0  2019    10     1       10
1  2019     4     2        8
2  2019    25     1       25
3  2018     3     1        4
4  2017    56     2       54
5  2017     3     2        1
Run Code Online (Sandbox Code Playgroud)

如果Year在索引中

df.assign(new_col=[op[t.Index](t.col1, t.col2) for t in df.itertuples()])

      col1  col2  new_col
Year                     
2019    10     1       10
2019     4     2        8
2019    25     1       25
2018     3     1        4
2017    56     2       54
2017     3     2        1
Run Code Online (Sandbox Code Playgroud)