循环计算数据帧中每个相同列值的最后一个和第三个值的差异

com*_*log 1 python loops dataframe pandas

我试图计算数据集中每列(ex1,ex2,...)的特定月份和年份的最后一个和第三个值之间的差异,然后保存到新的数据框中。

我的数据集如下所示:

前1 前2
12 1995年 55 55
12 1995年 46 33
12 1995年 33 12
12 1995年 15 17 号
12 1995年 6 16
12 1995年 35 32
12 1995年 67 22
12 1995年 43 25
12 1995年 31 26
12 1995年 34 11
12 1995年 53 14
12 1995年 72 60
1 1996年 34 90
1 1996年 55 14
1 1996年 58 24
1 1996年 54 23
1 1996年 33 20
1 1996年 24 45
1 1996年 23 33
1 1996年 15 38
1 1996年 11 50
1 1996年 79 55
1 1996年 80 71
1 1996年 88 74

例如,我想计算ex1

  • 1995 年 12 月的最后值 -> 72

  • 1995 年 12 月的第三个值 -> 33

  • 差值:72 - 33 = 39

  • 1996 年第 1 个月的最后值 -> 88

  • 1996 年 1 月的第三个值 -> 58

  • 差值:88 - 58 = 30

对于ex2

  • 1995 年 12 月的最后值 -> 88

  • 1995 年 12 月的第三个值 -> 58

  • 差值:88 - 58 = 30

  • 1996 年第 1 个月的最后值 -> 74

  • 1996 年 1 月的第三个值 -> 24

  • 差值:74 - 24 = 50

之后,我想将这些值写入一个新的数据帧,如下所示:

姓名 不同之处
前1 12 1995年 39
前1 1 1996年 30
前2 12 1995年 30
前2 1 1996年 50

我尝试执行以下操作:

df = pd.read_excel ('dataset') #See above
df_new = pd.DataFrame(columns=["Name","Month","Year","Difference"])

for colname, colitems in df.iloc.[:,2:].iteritems():
    for rownum, rowitem in colitems.iteritems():

        if (df["month"][rownum] != df["month"][rownum+1]) & (df["year"][rownum] != df["year"][rownum+1]):
            last= df[colname][rownum]
            third= df[colname][2]
            diff = last - third
            df_new.assign(name = df[colname][rownum], month = df["month"][rownum], 
                                    year= df["year"][rownum], difference= diff)
Run Code Online (Sandbox Code Playgroud)

当我尝试运行它时,我在if子句中遇到了KeyError: 79

另外,我的代码仅计算ex1的第 12 个月和 1995 年的差异。我怎样才能继续到下个月和下一年以及下一个值:ex2。我的方向正确吗?您有什么建议可以帮助我解决问题吗?

如果我遗漏了任何有助于解决此问题的内容,请告诉我,以便我立即纠正。

our*_*os1 5

您正在寻找的基本操作是一行:

res = df.groupby(['month','year']).last() - df.groupby(['month','year']).nth(2)
print(res)

            ex1  ex2
month year          
1     1996   30   50
12    1995   39   48
Run Code Online (Sandbox Code Playgroud)

为了使其达到您想要的输出形状,请尝试如下:

res.reset_index(drop=False,inplace=True)
res.sort_values(['year','month'], inplace=True)

res = pd.melt(res, 
              id_vars=['month','year'], 
              value_vars=['ex1','ex2'], 
              var_name = 'name', 
              value_name='difference')

res = res.loc[:, ['name','month','year','difference']]
print(res)

  name  month  year  difference
0  ex1     12  1995          39
1  ex1      1  1996          30
2  ex2     12  1995          48
3  ex2      1  1996          50
Run Code Online (Sandbox Code Playgroud)