如何在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 :用 “无 “替换除最常出现的元素外的每个元素。
# 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)
输出 :