2016-11-05 105 views
1

我在使用大熊猫列名称的数据透视表时遇到了麻烦。大熊猫数据透视表:用行数除以的问题

在这里我的问题

from collections import OrderedDict 
import pandas as pd 


table = OrderedDict((
("Item", ['Item0', 'Item0', 'Item1', 'Item1']), 
('CType',['Gold', 'Bronze', 'Gold', 'Silver']), 
('USD', [1, 2, 3, 4]), 
('EU', [1, 2, 3, 4]) 
)) 
d = pd.DataFrame(table) 

print d 

p = d.pivot_table(index='Item', columns='CType', values='USD') 
print p 

p.fillna(0, inplace=True) 
print p 

下面的操作给我楠一个奇怪的形状。 我错过了什么?

p/p.sum(axis = 1) 

PS:数据的例子,从here拍摄,但我自己的数据显示相同的行为

回答

3

使用DF.div代替:

p.div(p.sum(1), 0) 

enter image description here

axis=1在afore-上述方法的行为与您之前完成的方式类似,导致所有Nans

您必须通过提供axis=0来使其按行计算(沿索引)。

+1

感谢Nickil。这很棒,并按预期工作。然而,我仍然想知道如何处理来自枢轴操作的“命名列”。将发布一个单独的问题 – user1043144