Search code examples
pythonpandasoopsumoperation

Having trouble to sum values in a column that match a given condition


I am trying to sum the numeric values of one column depending on the value of another column. For example: whenever in the first column there is a Glovoapp I would like to sum its corresponding numeric values (of another column) together.

Table example:

Initiator Price
Glovoapp 566
XXXXX 545
Glovoapp 899
XXXXX 200
montant_init = new_data.loc[new_data['Initiateur'] == 'Glovoapp', 'Price'].sum()

output: 0 (none)
expected output (example): 1465

Solution

  • Use:

    montant_init = df[df["Initiator"]=="Glovoapp"]["Price"].sum()
    

    Alternatively you can use groupby if you have multiple Initiators:

    price_sum = df.groupby("Initiator")["Price"].sum()
    

    output:

    Initiator
    Glovoapp    1465
    XXXXX        745
    

    Then

    price_sum["Glovoapp"]
    

    outputs:

    1465