样本数据:
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
答案 0 :(得分:1)
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
答案 1 :(得分:0)
您想要的是获得一系列满足您想要的条件的索引。在您的情况下,条件是 user == Alice
。我在您的数据框中添加了额外的条目以使其更加清晰。所以:
import pandas as pd
df = pd.DataFrame({'user': ['Mike', 'Jim', 'Bob', 'Jane', 'Alice', 'Mike', 'Jim', 'Bob', 'Jane', 'Alice', 'Mike', 'Alice', 'Mike', 'Jim',],
'income': [45000,55000, 40000, 50000, 42000, 45000,55000, 40000, 50000, 42000, 55000, 40000, 50000, 42000],
'age' : [20,31,40,35,20, 20,31,40,35,20, 40,35,20, 20]})
cond_idx = df[df.loc[:, "user"]=="Alice"].index
cond_idx
现在有值
Int64Index([4, 9, 11], dtype='int64')
现在您可以遍历 cond_idx
并在数据帧上使用 .loc
来获取您想要的切片:
for idx in cond_idx:
result = df.loc[idx-2:idx, ["age", "income"]]
print(result)
输出:
age income
2 40 40000
3 35 50000
4 20 42000
age income
7 40 40000
8 35 50000
9 20 42000
age income
9 20 42000
10 40 55000
11 35 40000
答案 2 :(得分:0)
找到符合条件的行索引
alices = df[df.user=='Alice'].index
为每个索引的前三个索引创建一个数组。
indices = alices.values[:,None] - [3,2,1]
将这些索引与 .iloc
print(df.iloc[indices.ravel()])
>>> indices
array([[ 1, 2, 3],
[ 6, 7, 8],
[ 8, 9, 10]], dtype=int64)
>>> indices.ravel()
array([ 1, 2, 3, 6, 7, 8, 8, 9, 10], dtype=int64)
>>>
答案 3 :(得分:0)
我不确定这是否是您要查找的内容,但我相信这就是您在代码中尝试执行的操作:
df = pd.DataFrame({'user': ['Mike', 'Jim', 'Bob', 'Jane', 'Alice'],
'income': [45000,55000, 40000, 50000, 42000],
'age' : [20,31,40,35,20]})
df2=[]
def search(name):
for i in range(len(df['user'])):
if name == df['user'][i]:
df2=pd.DataFrame({'age':[df['age'][i]], 'income':[df['income'][i]]})
print(df2)
search('Alice')