+ 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
5 Respuestas
+ 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.
+ 1
please show your code in code playground.
It is only a fragment you show here.
hard to hel this way.
+ 1
Exactly as you did in the #This works example, so you already have the solution :)
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
0
Thanks Tibor Santa. So is there a way to get it to re-write back to the list within the same loop?