Virendra Patel
Virendra Patel

Reputation: 43

how to use divided in pandas pivot function

I want to divide the sum value in aggfun by 2 .

i want to this result :-

enter image description here

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B','B', 'B','A', 'A','A', 'B',],
                   'points_for': ['18', '22', '19', '14', '14', '11', '20', '28'],
                   'points_against': ['aa','bb','aa','bb','aa','bb','aa','bb']})

df2 = pd.pivot_table(df, values='points_for', index='team', columns='points_against', aggfunc=sum)
df2

enter image description here

Upvotes: 1

Views: 189

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195543

Try:

print(df2.astype(int) / 2)

Prints:

points_against       aa        bb
team                             
A               90710.0       5.5
B                   9.5  110714.0

Upvotes: 1

Ynjxsjmh
Ynjxsjmh

Reputation: 30050

You can divide after pivot

df2 = (pd.pivot_table(df, values='points_for', index='team', columns='points_against', aggfunc=sum)
       .astype(int).div(2))
print(df2)

points_against       aa        bb
team
A               90710.0       5.5
B                   9.5  110714.0

Upvotes: 1

Related Questions