给定一个具有不同分类变量的数据帧,如何返回包含百分比而不是频率的交叉列表?
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
我们可以用
100
来表示百分比:为了方便我绕了一圈。
基本上,您只需要使用
row/row.sum()
函数,然后使用apply
和axis=1
逐行应用它。(如果在Python 2中执行此操作,则应使用
from __future__ import division
确保division始终返回一个浮点数。)从Pandas 0.18.1开始,有一个
normalize
选项:可以在
all
、index
(行)或columns
之间进行正规化。更多详细信息请参见in the documentation。
相关问题 更多 >
编程相关推荐