Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to Series in python/pandas not working

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!

like image 391
Nick Avatar asked Dec 20 '16 04:12

Nick


People also ask

Can you append to a Pandas series?

Pandas Series: append() functionThe append() function is used to concatenate two or more Series. Series to append with self. If True, do not use the index labels. If True, raise Exception on creating index with duplicates.

How do you append a series to a DataFrame in Python?

append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value. ignore_index : If True, do not use the index labels.

How do I add items to Pandas series?

Step1: Define a Pandas series, s1. Step 2: Define another series, s2. Step 3: Append s2 to s1. Step 4: Print the final appended series.


2 Answers

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!

like image 63
cdonts Avatar answered Sep 16 '22 13:09

cdonts


The Series.append documentation states that append rows of other to the end of this frame, returning a new object.

The examples are a little confusing as it appears to show it working but if you look closely you'll notice they are using interactive python which prints the result of the last call (the new object) rather than showing the original object.

The result of calling append is actually a brand new Series.

In your example you would need to assign q each time to the new object returned by .append:

q = pd.Series([])
while i < len(other array):
    diff = some int value
    a = pd.Series([diff], ignore_index=True)
    # change of code here
    q = q.append(a)
    i+=1
like image 22
Rishab P Avatar answered Sep 20 '22 13:09

Rishab P