pandas.DataFrame.mode #

数据框。模式( axis = 0 , numeric_only = False , dropna = True ) [来源] #

获取沿选定轴的每个元素的模式。

一组值的众数是出现次数最多的值。它可以是多个值。

参数
{0 或 'index', 1 或 'columns'}, 默认 0

搜索模式时要迭代的轴:

  • 0 或 'index' : 获取每列的众数

  • 1 或 'columns' :获取每行的众数。

numeric_only布尔值,默认 False

如果为 True,则仅适用于数字列。

dropna bool,默认 True

不考虑 NaN/NaT 的计数。

返回
数据框

每列或行的众数。

也可以看看

Series.mode

返回系列中的最高频率值。

Series.value_counts

返回系列中值的计数。

例子

>>> df = pd.DataFrame([('bird', 2, 2),
...                    ('mammal', 4, np.nan),
...                    ('arthropod', 8, 0),
...                    ('bird', 2, np.nan)],
...                   index=('falcon', 'horse', 'spider', 'ostrich'),
...                   columns=('species', 'legs', 'wings'))
>>> df
           species  legs  wings
falcon        bird     2    2.0
horse       mammal     4    NaN
spider   arthropod     8    0.0
ostrich       bird     2    NaN

默认情况下,不考虑缺失值,wings的众数都是0和2。因为生成的DataFrame有两行,所以第二行specieslegs包含NaN

>>> df.mode()
  species  legs  wings
0    bird   2.0    0.0
1     NaN   NaN    2.0

考虑设置dropna=False NaN值,它们可以是模式(如翅膀)。

>>> df.mode(dropna=False)
  species  legs  wings
0    bird     2    NaN

设置 时numeric_only=True,仅计算数值列的众数,忽略其他类型的列。

>>> df.mode(numeric_only=True)
   legs  wings
0   2.0    0.0
1   NaN    2.0

要计算列而不是行的众数,请使用 axis 参数:

>>> df.mode(axis='columns', numeric_only=True)
           0    1
falcon   2.0  NaN
horse    4.0  NaN
spider   0.0  8.0
ostrich  2.0  NaN