Append to Series in python/pandas not working

Nick picture Nick · Dec 20, 2016 · Viewed 20.5k times · Source

I am trying to append values to a pandas Series obtained by finding the difference between the nth and nth + 1 element:

q = pd.Series([])

while i < len(other array):
    diff = some int value
    a = pd.Series([diff], ignore_index=True)
    q.append(a)
    i+=1

The output I get is:

Series([], dtype: float64)

Why am I not getting an array with all the appended values?

--

P.S. This is a data science question where I have to find state with the most counties by searching through a dataframe. I am using the index values where one state ends and the next one begins (the values in the array that I am using to find the difference) to determine how many counties are in that state. If anyone knows how to solve this problem better than I am above, please let me know!

Answer

cdonts picture cdonts · Dec 20, 2016

The append method doesn't work in-place. Instead, it returns a new Series object. So it should be:

q = q.append(a)

Hope it helps!