首页 > 解决方案 > 为每组行按行迭代的最有效方法是什么?

问题描述

我想知道如何有效地按组循环遍历行。所以就像下面的示例数据集显示的那样,它包括 3 名不同的学生以及他们在 3 个月内的通过记录。

import pandas as pd
import numpy as np
df = pd.DataFrame({'student':'A A A B B B C C C'.split(),
                  'month':[1, 2, 3, 1, 2, 3, 1, 2, 3],
                  'pass':[0, 1, 0, 0, 0, 0, 1, 0, 0]})
print(df)
 student  month  pass
0       A      1     0
1       A      2     1
2       A      3     0
3       B      1     0
4       B      2     0
5       B      3     0
6       C      1     1
7       C      2     0
8       C      3     0

我想要一个新列“pass_patch”,一开始应该等于“pass”。但是当一个学生的“pass”为 1 时,他在接下来的几个月中所有的“pass_patch”都应该是 1,如下所示:

df = pd.DataFrame({'student':'A A A B B B C C C'.split(),
                   'month':[1, 2, 3, 1, 2, 3, 1, 2, 3],
                   'pass':[0, 1, 0, 0, 0, 0, 1, 0, 0],
                   'pass_patch':[0, 1, 1, 0, 0, 0, 1, 1, 1]})
print(df)
  student  month  pass  pass_patch
0       A      1     0           0
1       A      2     1           1
2       A      3     0           1
3       B      1     0           0
4       B      2     0           0
5       B      3     0           0
6       C      1     1           1
7       C      2     0           1
8       C      3     0           1

我做了一些搜索,发现 iterrows 可能有效,但担心运行整个数据集(大约百万条记录)会太慢。会有更有效的方法来实现这一点吗?

任何建议将不胜感激。

标签: pythonpandasdataframe

解决方案


尝试cummax

df['new'] = df.groupby('student')['pass'].cummax()
df
Out[78]: 
  student  month  pass  new
0       A      1     0    0
1       A      2     1    1
2       A      3     0    1
3       B      1     0    0
4       B      2     0    0
5       B      3     0    0
6       C      1     1    1
7       C      2     0    1
8       C      3     0    1

推荐阅读