[英]How do I count only unique values with groupby using pandas/python?
What can I do to this pandas dataframe to get it to count only the unique/distinct values of "Unique_Id"?我可以对这个 Pandas 数据框做些什么来让它只计算“Unique_Id”的唯一/不同值? Everything I have tried gives me unique values of community instead, or throws an error.我尝试过的一切都给了我独特的社区价值观,否则会引发错误。
df.groupby("Community")["Unique_Id"].count().sort_values(ascending = False)
This is the output I get:这是我得到的输出:
Comunidad_Autónoma
Cataluña 534415
Comunidad Valenciana 475411
Madrid 415047
Islas Canarias 171939
País Vasco 168297
Navarra 57045
La Rioja 26057
Name: Unique_Id, dtype: int64
One possible option is to use pandas.DataFrame.drop_duplicates before you call the groupby method.一种可能的选择是在调用 groupby 方法之前使用pandas.DataFrame.drop_duplicates 。 In the example below, Madrid has a duplicate Id:在下面的示例中,马德里有一个重复的 ID:
import pandas as pd
df = pd.DataFrame(dict(
Community = 'Cataluña,Madrid,Cataluña,Madrid,Cataluña,Madrid'.split(','),
Unique_Id = [1, 2, 3, 4, 5, 2],
))
df1 = df.drop_duplicates(
['Community','Unique_Id']
).groupby(
'Community'
)['Unique_Id'].count().sort_values(ascending = False)
print(df1)
print(f'\nTotal Unique_Ids Across All Communities: {sum(df1.values)}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.