I have a list "profiles" looking like this for each element of the list: enter image description here
I want to create a dataframe out of this list, so that every account is in the dataframe. When I create one dataframe for every element of the list manually and then append them all to one dataframe it works. However, I wanted to do a loop because I have about 40 elements in that list.
The code looks as follows (doing it manually):
df2 = pd.DataFrame(profiles[1])
df1 = df1.append(df2)
df3 = pd.DataFrame(profiles[2])
df1 = df1.append(df3)
... and so on
My loop looks like this:
for y in range(len(profiles)):
if x != y:
df1 = pd.DataFrame(profiles[x])
df2 = pd.DataFrame(profiles[y])
df1.append(df2)
Does anybody know how to make the loop work? Because it does not append the second dataframe.
CodePudding user response:
you are overwriting your df1 in each iteration of the loop
IIUC, In the absence of the reproducible data and example, this is what you should add to your code
outside of the for loop, create an empty dataframe
df_final = pd.DataFrame()
inside the loop
df_final = pd.concat([df_final, df1], axis=1)
if your df1 and df2 both gets initialized in each iteration, then you can add them both to the df_final together as follows
df_final = pd.concat([df_final, df1, df2], axis=1)
at the end of the loop df_final will have all the df's appended to it
CodePudding user response:
append is not an inPlace Operation, so you have to assign the result of the function (otherwise it gets lost)