Home > Blockchain >  how to use divided in pandas pivot function
how to use divided in pandas pivot function

Time:10-24

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

CodePudding user response:

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

CodePudding user response:

Try:

print(df2.astype(int) / 2)

Prints:

points_against       aa        bb
team                             
A               90710.0       5.5
B                   9.5  110714.0
  • Related