Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prepend pandas data frames

Tags:

pandas

How can I prepend a dataframe to another dataframe? Consider dataframe A:

b c d
2 3 4
6 7 8

and dataFrame B:

a
1
5

I want to prepend A to B to get:

a b c d
1 2 3 4
5 6 7 8
like image 640
TheoretiCAL Avatar asked Jun 21 '13 00:06

TheoretiCAL


2 Answers

Achieved by doing

A[B.columns]=B
like image 114
TheoretiCAL Avatar answered Sep 27 '22 16:09

TheoretiCAL


2 methods:

In [1]: df1 = DataFrame(randint(0,10,size=(12)).reshape(4,3),columns=list('bcd'))

In [2]: df1
Out[2]: 
   b  c  d
0  5  9  5
1  8  4  0
2  8  4  5
3  4  9  2

In [3]: df2 = DataFrame(randint(0,10,size=(4)).reshape(4,1),columns=list('a'))

In [4]: df2
Out[4]: 
   a
0  4
1  9
2  2
3  0

Concating (returns a new frame)

In [6]: pd.concat([df2,df1],axis=1)
Out[6]: 
   a  b  c  d
0  4  5  9  5
1  9  8  4  0
2  2  8  4  5
3  0  4  9  2

Insert, puts a series into an existing frame

In [8]: df1.insert(0,'a',df2['a'])

In [9]: df1
Out[9]: 
   a  b  c  d
0  4  5  9  5
1  9  8  4  0
2  2  8  4  5
3  0  4  9  2
like image 38
Jeff Avatar answered Sep 27 '22 15:09

Jeff