如何用百分比制作Pandas交叉表?

2024-10-05 15:18:21 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个具有不同分类变量的数据帧,如何返回包含百分比而不是频率的交叉列表?

df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 6,
                   'B' : ['A', 'B', 'C'] * 8,
                   'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 4,
                   'D' : np.random.randn(24),
                   'E' : np.random.randn(24)})


pd.crosstab(df.A,df.B)


B       A    B    C
A               
one     4    4    4
three   2    2    2
two     2    2    2

使用crosstab中的margins选项来计算行和列的总数,使我们足够接近于认为使用aggfunc或groupby应该是可能的,但是我那微薄的大脑无法将其考虑清楚。

B       A     B    C
A               
one     .33  .33  .33
three   .33  .33  .33
two     .33  .33  .33

Tags: 数据dffoonp分类barrandomone
3条回答

我们可以用100来表示百分比:

pd.crosstab(df.A,df.B, normalize='index')\
    .round(4)*100

B          A      B      C
A                         
one    33.33  33.33  33.33
three  33.33  33.33  33.33
two    33.33  33.33  33.33

为了方便我绕了一圈。

pd.crosstab(df.A, df.B).apply(lambda r: r/r.sum(), axis=1)

基本上,您只需要使用row/row.sum()函数,然后使用applyaxis=1逐行应用它。

(如果在Python 2中执行此操作,则应使用from __future__ import division确保division始终返回一个浮点数。)

从Pandas 0.18.1开始,有一个normalize选项:

In [1]: pd.crosstab(df.A,df.B, normalize='index')
Out[1]:

B              A           B           C
A           
one     0.333333    0.333333    0.333333
three   0.333333    0.333333    0.333333
two     0.333333    0.333333    0.333333

可以在allindex(行)或columns之间进行正规化。

更多详细信息请参见in the documentation

相关问题 更多 >