首页 > 解决方案 > 选择满足条件的当前行和上面的 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

标签: pythonpandas

解决方案


IIUC groupbycumsum得到第一组和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

推荐阅读