Pandas分组去重

6
这是我的CSV文件的样子,
name, cuisine, review
A, Chinese, this
A, Indian, is
B, Indian, an
B, Indian, example
B, French, thank
C, French, you

我正在尝试计算不同种类的菜肴按名称出现的次数。这是我应该得到的结果。
Cuisine, Count
Chinese, 1
Indian, 2
French, 2

但是,您可以看到名称中存在重复项,例如B,因此我尝试使用drop_duplicates删除重复项,但我无法成功。我使用

df.groupby('name')['cuisine'].drop_duplicates() 

提示说系列groupby对象无法处理。

不知怎么的,我需要应用value_counts()来获取菜系单词出现的次数,但重复项会妨碍我的操作。你有什么办法可以在pandas中解决这个问题吗?谢谢。

2个回答

4
你需要使用 groupbynunique
df.groupby('cuisine', sort=False).name.nunique().to_frame('count')

         count
cuisine       
Chinese      1
Indian       2
French       2

会返回每个组中唯一项的数量。

2
使用表格
pd.crosstab(df.name,df.cuisine).ne(0).sum()
Out[550]: 
cuisine
 Chinese    1
 French     2
 Indian     2
dtype: int64

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接