ironzionlion
ironzionlion

Reputation: 889

Append lists to list of lists

I want to append lists of dataframes in an existing list of lists:

df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                     'B': ['B0', 'B1', 'B2', 'B3'],
                     'C': ['C0', 'C1', 'C2', 'C3'],
                     'D': ['D0', 'D1', 'D2', 'D3']},
                    index=[0, 1, 2, 3])


fr_list = [[] for x in range(2)]
fr_list[0].append(df1)
fr_list[0].append(df1)
fr_list[1].append(df1)


fr2 = [[] for x in range(2)]
fr2[0].append(df1)
fr2[1].append(df1)

fr_list.append(fr2)  # <-- here is the problem

Output: fr_list = [[df1, df1], [df1], [fr2[0], fr2[1]]] List contains 3 elements

Expected: fr_list = [[df1, df1, fr2[0]],[df1, fr2[1]]] List contains 2 elements

Upvotes: 0

Views: 108

Answers (1)

Mehul Gupta
Mehul Gupta

Reputation: 1939

fr_list=[a+b for a,b in zip(fr_list,fr2)]

Replace fr_list.append(fr2) with the above code

Explanation: using zip & list comprehension, add corresponding lists in fr_list & fr2. What you did was appended the outer list in fr_list with outer list in fr & not the inner lists.

output

Upvotes: 2

Related Questions