pythonpandasdataframe

How to add a new row to an existing DataFrame which is the sum of two rows?


I have a DataFrame looks as follow:

      Name1  Name2
Val1    1.2    2.2
Val2    2.3    4.2 

What I want is as follow:

      Name1  Name2
Val1    1.2    2.2
Val2    2.3    4.2 
Val3   0.52   0.52

The values in Val3 is Val1/Vals2.

How to do that?


Solution

  • Use .loc to grab each row individually and divide them. Use .append to append the result to the end of the original data frame.

    # Mocking up your example data.
    df = pd.DataFrame({'Name1':(1.2, 2.3), 'Name2':(2.2, 4.2)}, index=('Val1', 'Val2'))
    
    # The solution
    new_row = df.loc['Val1'] / df.loc['Val2']
    new_row.name = 'Val3'
    df.append([new_row])