更新时间:2022-12-11 21:49:33
如果Fruit
列中的所有值总是只有Apple
或Strawberry
您可以比较每组的集合,然后通过 True
的值的 sum
计算 ID
:
If always all values are only Apple
or Strawberry
in column Fruit
you can compare sets per groups and then count ID
by sum
of True
s values:
v = ['Apple','Strawberry']
out = df.groupby('ID')['Fruit'].apply(lambda x: set(x) == set(v)).sum()
print (out)
2
如果有很多值:
s = df.groupby('ID')['Fruit'].agg(frozenset).value_counts()
print (s)
{Apple} 2
{Strawberry, Apple} 2
{Strawberry} 1
Name: Fruit, dtype: int64