Transpose with for loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Transpose with for loop

I have a list (loads) which contains a number of pandas dataframes of the same size. I need to transpose all these dataframe. Can anyone please explain why the following won't work: for load in loads: load=load.T whereas this option does work: for ii in range(len(loads)): loads[ii]=loads[ii].T

12th Feb 2020, 5:23 AM
Raffaele
Raffaele - avatar
5 Answers
+ 2
for df in mylist: df=df.T This won't work because you are just assigning a new value to the loop variable, but it is not written back to the list.
12th Feb 2020, 10:04 AM
Tibor Santa
Tibor Santa - avatar
+ 1
please show your code in code playground. It is only a fragment you show here. hard to hel this way.
12th Feb 2020, 7:19 AM
Oma Falk
Oma Falk - avatar
+ 1
Exactly as you did in the #This works example, so you already have the solution :)
12th Feb 2020, 10:41 AM
Tibor Santa
Tibor Santa - avatar
0
Hi Oma, here's something you can work with: import numpy as np import pandas as pd # Create a list of dataframes mylist=[] for ii in range(5): mylist.append(pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD'))) # This works for ii in range(len(mylist)): mylist[ii]=mylist[ii].T # This does not work for df in mylist: df=df.T
12th Feb 2020, 7:45 AM
Raffaele
Raffaele - avatar
0
Thanks Tibor Santa. So is there a way to get it to re-write back to the list within the same loop?
12th Feb 2020, 10:24 AM
Raffaele
Raffaele - avatar