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
3
  • 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] Commented May 4, 2022 at 4: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() Commented May 4, 2022 at 5:12
  • Can you check your output please? Update the expected result for ex2 and ex3. Commented May 4, 2022 at 6:41

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.