user1043144
user1043144

Reputation: 2710

pandas pivot table : trouble with dividing by sum of rows

I am having trouble using a a pivot table with columns names in pandas.

here my problem

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

The following operation gives me NaN in a weird shape. What am I missing ?

 p / p.sum(axis = 1)

P.S: the example of the data is taken from here but my own data show same behaviour

Upvotes: 2

Views: 2679

Answers (1)

Nickil Maveli
Nickil Maveli

Reputation: 29711

Use DF.div instead:

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

enter image description here

axis=1 in the afore-mentioned method behaves in the similar manner as the way you've done before resulting in all Nans.

You have to make it compute row-wise(along the index) by supplying axis=0.

Upvotes: 6

Related Questions