pandas 如何在系列的开头附加/插入一个项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21994543/
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
how to append/insert an item at the beginning of a series?
提问by James Bond
imaging i have a series looks like this:
成像我有一个系列看起来像这样:
Out[64]: 
2      0
3      1
80     1
83     1
84     2
85     2
how can i append an item at the very beginning of this series? the native pandas.Series.append function only appends at the end.
我如何在本系列的开头附加一个项目?原生的 pandas.Series.append 函数只在最后追加。
thanks a lot
多谢
回答by ChrisP
There is a pandas.concatfunction...
有一个pandas.concat功能...
import pandas as pd
a = pd.Series([2,3,4])
pd.concat([pd.Series([1]), a])
See the Merge, Join, and Concatenate documentation.
请参阅合并、连接和连接文档。
回答by Victor Burnett
Using concat, or append, the resulting series will have duplicate indices:
使用 concat 或 append,生成的系列将具有重复的索引:
for concat():
对于 concat():
import pandas as pd
a = pd.Series([2,3,4])
pd.concat([pd.Series([1]), a])
Out[143]: 
0    1
0    2
1    3
2    4
and for append():
对于 append():
import pandas as pd
a = pd.Series([2,3,4])
a.append(pd.Series([1]))
Out[149]: 
0    2
1    3
2    4
0    1
This could be a problem in the future, since a[0] (if you assign the result to a) will return two values for either case.
这在未来可能会成为一个问题,因为 a[0](如果将结果分配给 a)将在任一情况下返回两个值。
My solutions are in this case:
我的解决方案是在这种情况下:
import pandas as pd
a = pd.Series([2,3,4])
b = [1]
b[1:] = a
pd.Series(b)
Out[199]: 
0    1
1    2
2    3
3    4
or, by reindexing with concat():
或者,通过使用 concat() 重新索引:
import pandas as pd
a = pd.Series([2,3,4])
a.index = a.index + 1  
pd.concat([pd.Series([1]), a])
Out[208]: 
0    1
1    2
2    3
3    4
回答by Joan Smith
Similarly, you can use append with a list or tuple of series (so long as you're using pandas version .13 or greater)
同样,您可以将 append 与一系列列表或元组一起使用(只要您使用的是 .13 或更高版本的 Pandas)
import pandas as pd
a = pd.Series([2,3,4])
pd.Series.append((pd.Series([1]), a))

