-
猛跑小猪
尝试对值agg进行切片。IDTrue对于更新的示例,您只需在处理之前删除重复项即可。其余的都一样df = df.drop_duplicates(['location', 'ID', 'Value'])df_agg = (df.Value.isin([1,2]).groupby(df.location) .agg(ID_count=lambda x: df.loc[x[x].index, 'ID'].nunique(), Value_count='sum'))Out[93]: ID_count Value_countlocationA 3 6B 4 7
-
饮歌长啸
与 anky 大致相同,但随后使用Series.whereandnamed aggregations因此我们可以在 groupby 中创建列时重命名列。grp = df.assign(Value=df['Value'].where(df['Value'].isin([1, 2]))).groupby('location')grp.agg( ID_count=('ID', 'nunique'), Value_count=('Value', 'count')).reset_index() location ID_count Value_count0 A 3 61 B 4 7
-
千巷猫影
让我们尝试使用与其他答案非常相似的方法。这次我们先过滤:(df[df['Value'].isin([1,2])] .groupby(['location'],as_index=False) .agg({'ID':'nunique', 'Value':'size'}))输出: location ID Value0 A 3 61 B 4 7
-
12345678_0001
IIUC,你可以尝试series.isin一下groupby.aggout = (df.assign(Value_Count=df['Value'].isin([1,2])).groupby("location",as_index=False) .agg({"ID":'nunique',"Value_Count":'sum'}))print(out) location ID Value_Count0 A 3 6.01 B 4 7.0