0

How to iterate over a list and assign each item to a variable until now i am able to iterate over the list and print all the items but i want to store each item in a variable in order to use it later like so.

Here i am hardcoding the variables... what i want is to assign values during the iteration.

code:

tl = pd.unique(df[item1].tolist())

var1 = df[item1][df[item1]==tl[0]]
var2 = df[item1][df[item1]==tl[1]]
var3 = df[item1][df[item1]==tl[2]]
var4 =df[item1][df[item1]==tl[3]]


print("number of var1  is: {}".format(len(var1)))
print("number of var2  is: {}".format(len(var2)))
print("number of var3  is: {}".format(len(var3)))
print("number of var4 is: {}".format(len(var4)))

what i want :

tl = pd.unique(df[item1].tolist())
                for column in tl:
                    print(column)
                    
Georges
  • 29
  • 8

2 Answers2

0
for index, row in df.T.iterrows():
    for c, x in enumerate(row.unique()):
        print(f'number of row{c+1} is: {x}')
Chris
  • 15,819
  • 3
  • 24
  • 37
0

Assuming n is the length of the list (you can have that easily) You can replace all this:

var1 = df[item1][df[item1]==tl[0]]
var2 = df[item1][df[item1]==tl[1]]
var3 = df[item1][df[item1]==tl[2]]
var4 = df[item1][df[item1]==tl[3]]
...
varn = df[item1][df[item1]==tl[n]]

With a list comprehension:

var = [df[item1][df[item1]==t] for t in tl]

Now to print:

for i in range(n):
    print(f"number of var{i}  is: {len(var[i])}")
RMPR
  • 3,368
  • 4
  • 19
  • 31