How to calculate the % of subtotal for multiple columns in pandas?

I want to calculate the percentage of subtotal of sales and cost. but I got TypeError: cannot convert the series to <class 'float'>

import numpy as np
import pandas as pd
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3, 'office_id': list(range(1, 7)) * 2, 'sales': [np.random.randint(100000, 999999) for _ in range(12)],
                   'cost': [np.random.randint(1000, 9999)  for _ in range(12)]})
state_office = df.groupby(['state', 'office_id']).agg({'sales': 'sum', 'cost': 'sum'})
# Change: groupby state_office and divide by sum
state_pcts = state_office.groupby(level=0).apply(lambda x: 100 * x / float(x.sum()))

Answer

have you tried after removing float :

import numpy as np
import pandas as pd

df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3, 'office_id': list(range(1, 7)) * 2,
                   'sales': [np.random.randint(100000, 999999) for _ in range(12)],
                   'cost': [np.random.randint(1000, 9999) for _ in range(12)]})
state_office = df.groupby(['state', 'office_id']).agg({'sales': 'sum', 'cost': 'sum'})
# Change: groupby state_office and divide by sum
state_pcts = state_office.groupby(level=0).apply(lambda x: 100 * x / x.sum())
print(state_pcts)

Gives

                     sales       cost
state office_id                      
AZ    2          42.683632  60.717383
      4          18.584491  11.374055
      6          38.731877  27.908562
CA    1          45.557943  14.629658
      3          39.376468  47.364924
      5          15.065589  38.005418
CO    1          28.811210  31.144523
      3          25.879458  31.911629
      5          45.309332  36.943848
WA    2          12.065239  55.277194
      4          34.076673  17.132698
      6          53.858088  27.590108