Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to append/insert an item at the beginning of a series?

Tags:

python

pandas

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.

thanks a lot

like image 790
James Bond Avatar asked Feb 24 '14 17:02

James Bond


Video Answer


2 Answers

There is a pandas.concat function...

import pandas as pd
a = pd.Series([2,3,4])
pd.concat([pd.Series([1]), a])

See the Merge, Join, and Concatenate documentation.

like image 65
ChrisP Avatar answered Sep 27 '22 22:09

ChrisP


Using concat, or append, the resulting series will have duplicate indices:

for 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():

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.

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():

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
like image 43
Victor Burnett Avatar answered Sep 27 '22 20:09

Victor Burnett