Nicolas Mellein
Nicolas Mellein

Reputation: 25

I can put this in a loop python?

can I put this into a loop??

Thanks a lot :)

    df0 = df0.groupby(['MNR'])['MENGE'].sum()
    df1 = df1.groupby(['MNR'])['MENGE'].sum()
    df2 = df2.groupby(['MNR'])['MENGE'].sum()
    df3 = df3.groupby(['MNR'])['MENGE'].sum()
    df4 = df4.groupby(['MNR'])['MENGE'].sum()

Upvotes: 0

Views: 38

Answers (2)

Mandera
Mandera

Reputation: 2992

Leo's answer is better IMO, but as an alternative if you want a more dynamic loop you can do something like this:

for key in list(locals().keys()):
    if key.startswith("df"):
        locals()[key] = locals()[key].groupby(['MNR'])['MENGE'].sum()

Upvotes: 0

Leo Arad
Leo Arad

Reputation: 4472

You can do a list with all the df's and then iterate over each one and apply the groupby and sum() on them.

dfs = [df0, df1, df2, df3, df4]
for df in dfs:
    df = df.groupby(['MNR'])['MENGE'].sum()

Upvotes: 1

Related Questions