猿问

使用 Pandas 中的条件计算多列中每个组的唯一值

更新了示例数据集


我有以下数据:


location ID  Value

A        1   1 

A        1   1

A        1   1 

A        1   1

A        1   2 

A        1   2

A        1   2 

A        1   2

A        1   3 

A        1   4 

A        2   1 

A        2   2 

A        3   1 

A        3   2

B        4   1 

B        4   2 

B        5   1

B        5   1 

B        5   2

B        5   2 

B        6   1 

B        6   1

B        6   1

B        6   1 

B        6   1

B        6   2

B        6   2

B        6   2   

B        7   1 


我想计算每个位置和以下输出的每个 ID 的唯一值(仅当值等于 1 或 2 时)。


location ID_Count  Value_Count

A        3         6

B        4         7

我尝试使用df.groupby(['location'])['ID','value'].nunique(),但我只得到唯一的值计数,就像我得到 A 的 value_count 为 4,B 的 value_count 为 2。


萧十郎
浏览 143回答 4
4回答

猛跑小猪

尝试对值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
随时随地看视频慕课网APP

相关分类

Python
我要回答