import pandas as pd
import numpy as np
raw_data = {'Country':['UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK'],
'Product':['A','A','A','A','B','B','B','B','B','B','B','B'],
'Week': [1,2,3,4,1,2,3,4,5,6,7,8],
'val': [5,4,3,1,5,6,7,8,9,10,11,12]
}
have = pd.DataFrame(raw_data, columns = ['Country','Product','Week', 'val'])
print(have)
我想选择产品A的最后一周之前和之后的行,即第4周和产品B的行应为4行,第3周之前应为3行,第5周之后应为5,6,包括第4周,因此总计为4。这是通缉的输出
答案 0 :(得分:1)
IIUC:
df = pd.DataFrame(raw_data, columns=['Country', 'Product', 'Week', 'val'])
max_week = df.loc[df["Product"].eq("A"),"Week"].max()
print (df[df["Product"].eq("A")|((df["Week"]>=max_week-1)&(df["Week"]<=max_week+2))])
#
Country Product Week val
0 UK A 1 5
1 UK A 2 4
2 UK A 3 3
3 UK A 4 1
6 UK B 3 7
7 UK B 4 8
8 UK B 5 9
9 UK B 6 10