有关以下解决方案的性能影响,请参阅Pandas groupby.size vs series.value_counts vs collections.Counter 具有多个系列 https://stackoverflow.com/questions/50328246/pandas-groupby-size-vs-series-value-counts-vs-collections-counter-with-multiple。下面首先介绍它们,其中性能最佳。
GroupBy.size https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html
您可以使用(姓名,姓氏)元组索引创建一系列计数GroupBy.size
:
res = df.groupby(['Name', 'Surname']).size().sort_values(ascending=False)
通过对这些值进行排序,我们可以轻松提取最常见的值:
most_common = res.head(1)
most_common_dups = res[res == res.iloc[0]].index.tolist() # handles duplicate top counts
value_counts https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html
另一种方法是构造一系列元组,然后应用pd.Series.value_counts
:
res = pd.Series(list(zip(df.Name, df.Surname))).value_counts()
结果将是一系列按姓名组合索引的计数,从最常见到最少排序。
name, surname = res.index[0] # return most common
most_common_dups = res[res == res.max()].index.tolist()
collections.Counter https://docs.python.org/3/library/collections.html#collections.Counter
如果你想创建一个字典(name, surname): counts
条目,您可以通过collections.Counter
:
from collections import Counter
zipper = zip(df.Name, df.Surname)
c = Counter(zipper)
Counter
有有用的方法,例如most_common
,您可以使用它来提取结果。