0

I have a code that return the max value of each column in the dataframe until now it returns a list of the correct items.

What I want is to assign each item into a variable where this variable is created inside the for loop over the list.

expected result:

  • var1=item0
  • var2=item1
  • var3=item2

where the var is a variable created by the iteration over the list.

if i run the code below it crash and return this error:

    for i, l in lgdf:
TypeError: cannot unpack non-iterable int object

code:

import pandas as pd

grouped_df=pd.crosstab(df['year_month'], df['event_type'])
lgdf =   list(grouped_df.max())

i = 0
for i, l in lgdf:
    var[i]=l
print(var)
Lelo Lelo
  • 17
  • 5
  • A list is the perfect storage for a list of items, why do you want individual variables instead? Still, see this question for iterating over a list with index: https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops – Wups Nov 11 '20 at 12:00
  • because i want display each variable in a different label but i do not know how many variables is created so that i want to iterate over the list – Lelo Lelo Nov 11 '20 at 12:05
  • Your code is incomplete. What's `df`, where is `var` declared? This bit of code won't run. – OctaveL Nov 11 '20 at 12:08

1 Answers1

0

Although I agree with the comment of @Wups that storing the values in a list (or dictionary) would work as well, you can do the following to create variables within a for loop.

for i, l in lgdf:
    exec(f'var_{i} = l')
Rik Kraan
  • 514
  • 1
  • 13