使用iterrows()比较多行的值



我想使用iterrows()来比较当前行和下一行的值。

代码是:

yc_df = pd.DataFrame([[7,1,1990,0], [7.5,1,1990,0], [8,2,1990,0],[8.5,2,1990,0]], columns=['3_Mo', 'Month','Year', 'Avg_3_Mo'])
#initially, yc_df['Avg_3_Mo'] has been initialised to all 0s.
for index, row in yc_df.iterrows():
if math.isnan(row['3_Mo']) == False:
count += 1
sum_3mo += row['3_Mo']
avg_3mo = sum_3mo/count 
if row['Month']!= (row+1)['Month']: **#Here I want to compare the current row value with the next row**
row['Avg_3_Mo'] = avg_3mo
sum_3mo = 0 
avg_3mo = 0

不知道如何使这个工作。

预期输出:

df
3_Mo  Month  Year  Avg_3_Mo
0  7      1     1990     0
1  7.5    1     1990     7.25
2  8      2     1990     0
3  8.5    2     1990     8.25

预期的输出应该包含要更新的'Avg 3 Mo'列,使用每个月和年的'3 Mo'的平均值(如GROUP BY 'Month', 'Year')。因此,我希望'Avg 3 Mo'对所有条目都有零,除了'Month'的值从一行更改到下一行的条目。对于'Month'值发生变化的这些行,我想输入月份的平均值。

IIUC,使用groupby平均值,然后mask每组的第一行:

g = yc_df.groupby(['Month', 'Year'])
yc_df['Avg_3_Mo'] = g['3_Mo'].transform('mean').mask(g.cumcount().eq(0), 0)

输出:

3_Mo  Month  Year  Avg_3_Mo
0   7.0      1  1990      0.00
1   7.5      1  1990      7.25
2   8.0      2  1990      0.00
3   8.5      2  1990      8.25

最新更新