附加到 python/pandas 中的系列不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41234822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append to Series in python/pandas not working
提问by Nick
I am trying to append values to a pandas Series obtained by finding the difference between the nth and nth + 1 element:
我试图将值附加到通过查找第 n 个和第 n + 1 个元素之间的差异获得的Pandas系列:
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!
PS 这是一个数据科学问题,我必须通过搜索数据框来找到拥有最多县的州。我正在使用一个州结束和下一个州开始的索引值(我用来查找差异的数组中的值)来确定该州有多少个县。如果有人比我上面知道如何更好地解决这个问题,请告诉我!
回答by cdonts
The append
method doesn't work in-place. Instead, it returns a new Series
object. So it should be:
该append
方法不能就地工作。相反,它返回一个新Series
对象。所以应该是:
q = q.append(a)
Hope it helps!
希望能帮助到你!
回答by Rishab P.
The Series.append documentation states that appendrows of other to the end of this frame, returning a new object.
Series.append 文档指出将other 的行附加到此帧的末尾,返回一个新对象。
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.
这些示例看起来有点令人困惑,因为它似乎表明它正在工作,但如果仔细观察,您会注意到它们使用交互式 python,它打印最后一次调用的结果(新对象),而不是显示原始对象。
The result of calling append is actually a brand new Series.
调用 append 的结果实际上是一个全新的Series。
In your example you would need to assign q each time to the new object returned by .append
:
在您的示例中,您每次都需要将 q 分配给由 返回的新对象.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