Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

list.append vs pd.series.append

I noticed that while list.append changes the original list, pd.series.append doesn’t change the original series:

b = [1,2,3,4,5]

b.append(9)

b

# returns [1, 2, 3, 4, 5, 9]
s = pd.Series([1,2,3,4,5])

s.append(pd.Series([9]))

s

# returns 
0    1
1    2
2    3
3    4
4    5

Despite using Python for quite a while I never realized this and spent a long time debugging because I kept getting errors or unintended values while running a for loop for a series using the ‘append’ method inside. Python is my first programming language btw.

Why is there a discrepancy although both are the same methods? Or is the ‘append’ method an exception? It gets personally confusing because it makes a huge difference in writing python code and getting the results I want. And it makes me wonder if there are similar discrepancies for other methods between lists and series(or dataframes) as well that I should be aware of.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m just a bit frustrated whenever I encounter these seemingly trivial things because I personally tend to forget them later on and repeat the same mistake.

Should I just memorize this and get over with it? I wish to know the approach I should take when trying to learn new things like these because I don’t know whether I’ll be able to remember these kinds of subtle differences as time passes. I would appreciate any good tips or advice.

>Solution :

In Pandas, the append method does NOT change the original DataFrame.

In contrast, append method of list changes target list.

Let’s take a look.

b = [1,2,3,4,5]

b.append(9)

b

# returns [1, 2, 3, 4, 5, 9] # target list 'b' has been changed.

Case of pandas.

import pandas as pd

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'), index=['x', 'y'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'), index=['x', 'y'])
df.append(df2)

df

# result = 
           A    B
        x  1    2
        y  3    4

So we have to assign clearly that we are going to change the DataFrame.
e.g.

df = df.append(df2) # this changes df.

df
# result =  A   B
        x   1   2
        y   3   4
        x   5   6
        y   7   8

Hopefully it helps 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading