python - 为每组行按行迭代的最有效方法是什么?
问题描述
我想知道如何有效地按组循环遍历行。所以就像下面的示例数据集显示的那样,它包括 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 可能有效,但担心运行整个数据集(大约百万条记录)会太慢。会有更有效的方法来实现这一点吗?
任何建议将不胜感激。
解决方案
尝试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
推荐阅读
- gcloud - Stackdriver 提醒政策未触发
- react-native - 为导航抽屉添加菜单按钮会出错
- java - 在 Android 中没有得到 USSD 代码的响应
- vue.js - 如何渲染一个包含 3 个项目和 2 列的循环,其中 1 个在第一列,另外 2 个在第 2 列?
- c++11 - 自己声明结构?
- oracle - 将 Informix 查询转换为 Oracle?
- vba - 循环遍历“条形样式”中的项目,阅读项目
- android - Android Google Play 商店应用程序不兼容 64 位
- unity3d - 如何更改附加了动画师的 UI 图像?
- ibm-cloud - Watson Assistant:我可以使用示例中的实体来定义意图吗?