问题描述
我有以下 df:
d = {'animal': ['lion','dog','cat','lion','shark','shark'],'age': [3,4,9,10,8,5,9]}
df_1 = pd.DataFrame(data=d)
我的目标是:
换句话说,如果来自 'animal' 列的值重复 3 次或更多,则从 df 中删除整行。在这种情况下: (lion:3,shark:2,cat:2,dog:1) -- 移除了狮子
我该如何解决这个问题?我正在迭代,但我被卡住了。有没有系列方法?如何接近?
解决方法
试试:
m=df_1['animal'].value_counts().ge(3)
#create a condition to check if the count of particular value is greater then or eq to 3 or not
最后:
out=df_1[~df_1['animal'].isin(m[m].index)]
#Finally Filter out result
out
的输出:
animal age
1 dog 4
2 cat 9
4 shark 8
5 cat 5
7 shark 9
如果需要,使用 reset_index()
方法:
out=out.reset_index(drop=True)
,
您可以将 GroupBy.transform
与 count
一起使用并应用布尔屏蔽。
m = df_1.groupby('animal')['animal'].transform('count').lt(3)
print(df_1[m])
animal age
1 dog 4
2 cat 9
4 shark 8
5 cat 5
7 shark 9