【问题标题】:pandas pivot table : trouble with dividing by sum of rows熊猫数据透视表:除以行总和的麻烦
【发布时间】:2016-11-05 14:31:09
【问题描述】:

我在使用带有 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,但我自己的数据显示相同的行为

【问题讨论】:

    标签: pandas pivot-table


    【解决方案1】:

    改用DF.div

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

    上述方法中的axis=1 的行为方式与您之前所做的方式相似,从而导致所有Nans

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

    【讨论】:

    • 感谢尼克尔。这很棒并且按预期工作。然而,我仍然想知道如何处理来自枢轴操作的“命名列”。将发布一个单独的问题
    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 2020-06-15
    • 2014-11-03
    • 2021-02-28
    • 2023-01-11
    • 2016-12-30
    • 2017-01-14
    相关资源
    最近更新 更多