1 回答
TA贡献2037条经验 获得超6个赞
如果你想在一行代码中结合 filter 和 groupby:
df = pd.DataFrame({'name' : ['ar street3', 'ar street3', 'ba foo', 'br', ' oo', 'ke'],
'month' : [1, 2, 3, 4, 5, 6],
'score' : [2.0, 5., 8., 1., 2., 9.]})
tag = 'ar street3'
df = df.groupby(['month', 'name']).filter(lambda x: tag in x.name)
print(df)
输出:
name month score
0 ar street3 1 2.0
1 ar street3 2 5.0
如果要添加月份条件:
tag = 'ar street3'; month = 1
df = df.groupby(['month', 'name']).filter(lambda x: tag in x.name and month == x.month)
name month score
0 ar street3 1 2.0
如果你只想要一个月:
#i have adapted the sample
df = pd.DataFrame({'name' : ['ar street3', 'ar street3', 'ba foo', 'br', ' oo', 'ke'],
'month' : [1, 2, 3, 4, 5, 1],
'score' : [2.0, 5., 8., 1., 2., 9.]})
month = 1
df = df.groupby(['month', 'name']).filter(lambda x: month == x.month)
输出:
name month score
0 ar street3 1 2.0
5 ke 1 9.0
添加回答
举报