python - 选择满足条件的当前行和上面的 3 行
问题描述
样本数据:
df = pd.DataFrame({'user': ['Mike', 'Jim', 'Bob', 'Jane', 'Alice'],
'income': [45000,55000, 40000, 50000, 42000],
'age' : [20,31,40,35,20]})
我希望能够从当前行和名字 = Alice 的任何人上方的 2 行中选择“用户”和“年龄”
这是我到目前为止所拥有的(不确定是否正确):
age2 = []
income2 = []
if df("user") in ['Alice']:
age2.append(df.attrib.get("age"))
income2.append(df.attrib.get("user"))
我希望有
age income
35 50000
40 40000
31 55000
解决方案
IIUC groupby
,cumsum
得到第一组和tail
:
print (df.groupby(df["user"].eq("Alice").cumsum()).get_group(0).tail(3))
user income age
1 Jim 55000 31
2 Bob 40000 40
3 Jane 50000 35
推荐阅读
- angular - 组件 BehaviorSubject 订阅者未收到从异步 http 请求发出的值
- angular - 我可以在 Angular 4 中使用哪个版本的 NgRx
- amazon-web-services - 将 S3 存储桶配置为仅在某些目录上允许 getObject 用于匿名
- c# - OR with integers
- heroku - 将 Heroku 应用子页面指向其自己的自定义域
- spring-boot - 响应正文错误的块标头 - GET 请求上的 I/O 错误
- java - 如何在 Java 9+ 中运行 XJC
- c# - Android模拟器未连接到localhost api
- c# - 来自基类的索引数据注释的异常
- java - 使用 Gson 在 Retrofit 中解析 JSON