Skip to content Skip to sidebar Skip to footer

Add A Calculated Row Below Each Row In A Pandas Data Frame

I have a pivot table dataframe that has columns with Counts of reason codes for a date range and location. Ideally I would like to insert a row under each location with the %age of

Solution 1:

Not sure this is the most elegant solution but it works:

input:

   Reason  CE  CS
0  (01,1)   131  (02,1)   412  (03,1)   373  (04,1)   254  (05,1)   045   total  1020

here is the code:

def calc_percent(x, total_values):
    x_array = x.values
    x_values = x_array[1:]
    new_x = [x_array[0]] + [str(100.0*x_values[i]/total_values[i]) +"%" for i in range(len(x_values))]
    return np.asarray(new_x)

total_row = df.iloc[-1,:]
total_values = total_row.values[1:]
rest_df = df.iloc[:-1, :]
new_df = rest_df.apply(lambda x: calc_percent(x,total_values),axis=1)
final_df = rest_df.append(new_df).sort_values("Reason")
final_df.loc[final_df.shape[0]] = total_row

output:

    Reason     CE     CS
0   (01,1)      130   (01,1)  10.0%15.0%1   (02,1)      411   (02,1)  40.0%5.0%2   (03,1)      372   (03,1)  30.0%35.0%3   (04,1)      253   (04,1)  20.0%25.0%4   (05,1)      044   (05,1)   0.0%20.0%10   total     1020

Post a Comment for "Add A Calculated Row Below Each Row In A Pandas Data Frame"