pandas.crosstab#

pandas.crosstab(index, columns, values=None, rownames=None, colnames=None, aggfunc=None, margins=False, margins_name='All', dropna=True, normalize=False)[源代码]#

计算两个(或多个)因子的简单交叉表。

默认情况下,除非传递了值数组和聚合函数,否则会计算因子的频率表。

Parameters:
indexarray-like, Series, or list of arrays/Series

用于行分组的值。

columnsarray-like, Series, or list of arrays/Series

用于列分组的值。

valuesarray-like, optional

用于根据因子进行聚合的值数组。需要指定 aggfunc

rownamessequence, default None

如果传递,则必须与传递的行数组的数量匹配。

colnamessequence, default None

如果传递,则必须与传递的列数组的数量匹配。

aggfuncfunction, optional

如果指定,则还需要指定 values

marginsbool,默认 False

添加行/列边距(小计)。

margins_name字符串,默认值为 ‘All’

margins 为 True 时,将包含总计的行/列名称。

dropnabool, default True

不包括条目全为 NaN 的列。

normalizebool, {‘all’, ‘index’, ‘columns’}, or {0,1}, default False

通过除以总值来归一化。

  • 如果传递 ‘all’ 或 True,则会对所有值进行归一化。

  • 如果传递 ‘index’,则会按每行进行归一化。

  • 如果传递 ‘columns’,则会按每列进行归一化。

  • 如果 marginsTrue,则也会对边距值进行归一化。

Returns:
DataFrame

数据的交叉表。

参见

DataFrame.pivot

根据列值重塑数据。

pivot_table

创建 DataFrame 作为枢轴表。

Notes

除非指定了交叉表的行或列名称,否则将使用传入的任何 Series 的名称属性。

传入的任何包含分类数据的输入都将包含其**所有**类别在交叉表中,即使实际数据不包含某个类别的任何实例。

如果没有重叠的索引,将返回一个空的 DataFrame。

参考 the user guide 获取更多示例。

Examples

>>> a = np.array(["foo", "foo", "foo", "foo", "bar", "bar",
...               "bar", "bar", "foo", "foo", "foo"], dtype=object)
>>> b = np.array(["one", "one", "one", "two", "one", "one",
...               "one", "two", "two", "two", "one"], dtype=object)
>>> c = np.array(["dull", "dull", "shiny", "dull", "dull", "shiny",
...               "shiny", "dull", "shiny", "shiny", "shiny"],
...              dtype=object)
>>> pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'])
b   one        two
c   dull shiny dull shiny
a
bar    1     2    1     0
foo    2     2    1     2

这里 ‘c’ 和 ‘f’ 在数据中不存在,并且由于 dropna 默认为 True,因此不会显示在输出中。将 dropna=False 设置为可以保留没有数据的类别。

>>> foo = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c'])
>>> bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f'])
>>> pd.crosstab(foo, bar)
col_0  d  e
row_0
a      1  0
b      0  1
>>> pd.crosstab(foo, bar, dropna=False)
col_0  d  e  f
row_0
a      1  0  0
b      0  1  0
c      0  0  0