📜  如何在 Pandas 系列中显示最常见的值?

📅  最后修改于: 2022-05-13 01:55:36.838000             🧑  作者: Mango

如何在 Pandas 系列中显示最常见的值?

在本文中,我们的基本任务是打印一系列中出现频率最高的值。我们可以使用 value_counts() 方法找到元素的出现次数。从中可以使用 mode() 方法访问最频繁的元素。

示例 1:

# importing the module
import pandas as pd
   
# creating the series
series = pd.Series(['g', 'e', 'e', 'k', 's', 
                    'f', 'o', 'r', 
                    'g', 'e', 'e', 'k', 's'])
print("Printing the Original Series:")
display(series)
  
# counting the frequency of each element
freq = series.value_counts()
print("Printing the frequency")
display(freq)
  
# printing the most frequent element
print("Printing the most frequent element of series")
display(series.mode());

输出 :

示例 2:用 None 替换除最常见元素之外的每个元素。

# importing the module
import pandas as pd
   
# creating the series
series = pd.Series(['g', 'e', 'e', 'k', 's', 
                    'f', 'o', 'r', 
                    'g', 'e', 'e', 'k', 's'])
  
# counting the frequency of each element
freq = series.value_counts()
  
# replacing everything else as Other
series[~series.isin(freq .index[:1])] = None
print(series)

输出 :