0

I attached an empty list of Dataframes into a variable. I used it in a for loop along with a list of columns so that I can transpose the columns into the index.

Then reassigned it back into the elements (the empty Dataframes). However, when I check it. The Dataframes are still empty. Why is that and how do I go about fixing it?

ex1 = pd.DataFrame({'col one':[100,200],'col two':[300,400]})
cols_list = ['col one', 'col two']

ex2 = pd.DataFrame()
ex3 = pd.DataFrame()
newdf_lists = [ex3, ex4]

for newdf_list, col_list in zip(newdf_lists, cols_list):
    newdf_list = ex1[col_list]
    newdf_list = newdf_list.transpose()

ex3

The result I get is:

__

The output I want is:

           0    1
col one   100   200
col two   300   400
Marc_Law
  • 25
  • 6
  • When you do `newdf_list = ex1[col_list]`, `newdf_list` references a new memory address and no longer `ex2` or `ex3`. If you want to modify the nth element of the list you need to use something like `newdf_lists[i] = ex1[col_list]` – Corralien May 04 '22 at 04:42
  • I'm still new to Python so I'm sorry if this is a noob question but where are you getting the [i] from? Do I have to do something like? for newdf_list, col_list in zip(newdf_lists, cols_list): for idx, row in newdf_list.itterows(): newdf_list[row] = ex1[col_list] newdf_list[row] = newdf_list[row].transpose() – Marc_Law May 04 '22 at 05:12
  • Can you check your output please? Update the expected result for `ex2` and `ex3`. – Corralien May 04 '22 at 06:41

1 Answers1

0
newdf_lists = [ex2, ex3]

for i in range (0, len(newdf_lists)):
        newdf_lists[i][cols_list[0]] = ex1[cols_list[0]]#col one
        newdf_lists[i][cols_list[1]] = ex1[cols_list[1]]#col two
        newdf_lists[i] = newdf_lists[i].transpose()

Note how columns for frames are created.

Output 'newdf_lists[0]'

           0    1
col one  100  200
col two  300  400

Output 'newdf_lists[1]'

           0    1
col one  100  200
col two  300  400
inquirer
  • 4,286
  • 2
  • 9
  • 16