pandas pivot table:除以行总和的问题

时间:2016-11-05 14:31:10

标签: pandas pivot-table

我在使用pandas中的列名称的数据透视表时遇到问题。

这是我的问题

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

以下操作为我提供了奇怪形状的NaN。 我错过了什么?

 p / p.sum(axis = 1)

P.S:数据示例取自here,但我自己的数据显示相同的行为

1 个答案:

答案 0 :(得分:3)

改为使用DF.div

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

enter image description here

上述方法中的

axis=1的行为方式与您之前完成Nans之前的方式相似。

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