问题
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!
回答1:
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!
回答2:
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
来源:https://stackoverflow.com/questions/41234822/append-to-series-in-python-pandas-not-working