Skip to content Skip to sidebar Skip to footer

Why Can't I Append Pandas Dataframe In A Loop

I know that there are several ways to build up a dataframe in Pandas. My question is simply to understand why the method below doesn't work. First, a working example. I can creat

Solution 1:

This happens because the .append() method returns a new df:

Pandas Docs (0.19.2):

pandas.DataFrame.append

Returns:appended:DataFrame

Here's a working example so you can see what's happening in each iteration of the loop:

df1 = pd.DataFrame([[1,2],], columns=['a','b'])
df2 = pd.DataFrame()
for i in range(0,2):
    print(df2.append(df1))

>    a  b
> 012
>    a  b
> 012

If you assign the output of .append() to a df (even the same one) you'll get what you probably expected:

for i in range(0,2):
    df2 = df2.append(df1)
print(df2)
>    a  b> 0  1  2> 0  1  2

Solution 2:

I think what you are looking for is:

df1 = pd.DataFrame()
df2 = pd.DataFrame([[1,2,3],], columns=['a','b','c'])


for i in range(0,4):
    df1 = df1.append(df2)

df1

Solution 3:

df.append() returns a new object. df2 is a empty dataframe initially, and it will not change. if u do a df3=df2.append(df1), u will get what u want

Post a Comment for "Why Can't I Append Pandas Dataframe In A Loop"