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



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

我的数据集如下所示:

ex1//tr>>33>>7274
ex2
12 1995 55
12 1995 46 33
12 199512
12 1995 15 17
12 1995 6 16
12 1995 35 32
12 1995 67 22
12 1995 4325
12 1995 31 26
12 1995 34 11
12 1995 53 14
12 199560
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

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

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

要使其成为您想要的输出,请尝试以下操作:

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
grp = df.groupby(['Month', 'Year'])

然后以下将返回您想要的差异,

grp.last() - grp.nth(2)

无需循环:(

编辑:这是我测试的同义示例——答案不是要求的形状,但数据是好的

df = pd.DataFrame(
{
"month": [1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2],
"year": [1999, 1999, 1999, 1999, 1999, 1999, 1999, 1999, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000],
"ex1": [11, 22, 33, 44, 55, 66, 77, 88, 22, 44, 66, 88, 1010, 1212, 1414, 1616],
"ex2": [22, 44, 66, 88, 1010, 1212, 1414, 1616, 11, 22, 33, 44, 55, 66, 77, 88],
}
)

返回以下内容:

>>>         
ex1  ex2
month year
1     1999   11   22
2000   22   11
2     1999   11  202
2000  202   11

相关内容

最新更新