[Python] How to use a for loop in a DataFrame?

Discussão em 'Python' iniciado por Stack, Janeiro 30, 2025.

  1. Stack

    Stack Membro Participativo

    I am not able to use a for loop with a DataFrame.

    My code is as follows:

    for i in data["categ"].unique():
    subset = data.loc[data["categ"]=="i",:]
    print(subset["montant"].sum())


    And here is the output:

    0.0
    0.0
    0.0
    0.0
    0.0
    0.0
    0.0


    When I get rid of the for loop and I do it manually, I get the correct values, instead of just zeros:

    subset = data.loc[data["categ"]=="LOYER",:]
    print(subset["montant"].sum())
    -2070.0


    How do I fix the for loop method?

    Continue reading...

Compartilhe esta Página