pandas的corsstab

 
pandas.crosstab(index, columns, values=None, rownames=None, colnames=None, aggfunc=None, margins=False, dropna=True, normalize=False)

index : array-like, Series, or list of arrays/Series

Values to group by in the rows

columns : array-like, Series, or list of arrays/Series

Values to group by in the columns

values : array-like, optional

Array of values to aggregate according to the factors. Requires aggfunc be specified.

aggfunc : function, optional

If specified, requires values be specified as well

rownames : sequence, default None

If passed, must match number of row arrays passed

colnames : sequence, default None

If passed, must match number of column arrays passed

margins : boolean, default False

Add row/column margins (subtotals)

dropna : boolean, default True

Do not include columns whose entries are all NaN

normalize : boolean, {‘all’, ‘index’, ‘columns’}, or {0,1}, default False

Normalize by dividing all values by the sum of values.

  • If passed ‘all’ or True, will normalize over all values.
  • If passed ‘index’ will normalize over each row.
  • If passed ‘columns’ will normalize over each column.
  • If margins is True, will also normalize margin values.

New in version 0.18.1.

In [1]:
import numpy as np
a = np.array(["foo", "foo", "foo", "foo", "bar", "bar","bar", "bar", "foo", "foo", "foo"], dtype=object)
a
In [2]:
b = np.array(["one", "one", "one", "two", "one", "one", "one", "two", "two", "two", "one"], dtype=object)
b
In [3]: 
pd.crosstab(a,b)
Out[3]:
col_0onetwo
row_0  
bar31
foo43
In [4]:
 pd.crosstab(a, b, rownames=['a'], colnames=['b'])
 
Out[4]:
bonetwo
a  
bar31
foo43
In [5] 
c = np.array(["dull", "dull", "shiny", "dull", "dull", "shiny","shiny", "dull", "shiny", "shiny", "shiny"],
               dtype=object)
c
In [6]:
import pandas as pd 
pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'])
Out[6]:
bonetwo
cdullshinydullshiny
a    
bar1210
foo2212
In [7]:
foo1 = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c'])
bar1= pd.Categorical(['d', 'e'], categories=['d', 'e', 'f'])
pd.crosstab(foo1, bar1,dropna='true')  
# 'c' and 'f' are not represented in the data,
# and will not be shown in the output because
# dropna is True by default. Set 'dropna=False'
# to preserve categories with no data 
 
Out[7]:
col_0def
row_0   
a100
b010
c000
 

转载于:https://www.cnblogs.com/wqbin/p/11146588.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值