Concat

Concatenating pandas objects together with concat():

In [1]:
import numpy as np
import pandas as pd
In [2]:
df = pd.DataFrame(np.random.randn(8, 2))
In [3]:
df
Out[3]:
0 1
0 -0.237914 -1.892821
1 0.041335 -2.332618
2 -0.410800 -0.940795
3 -1.586741 0.561043
4 1.257872 -2.087854
5 0.915597 1.942132
6 -0.720958 0.314698
7 0.173832 1.186308
In [4]:
pieces = [df[:3], df[3:4], df[6:]]
In [5]:
pd.concat(pieces)
Out[5]:
0 1
0 -0.237914 -1.892821
1 0.041335 -2.332618
2 -0.410800 -0.940795
3 -1.586741 0.561043
6 -0.720958 0.314698
7 0.173832 1.186308

Join

SQL style merges:

In [6]:
left = pd.DataFrame({'key': ['s1', 's1'], 'lval': [1, 2]})
left
Out[6]:
key lval
0 s1 1
1 s1 2
In [7]:
right = pd.DataFrame({'key': ['s1', 's1'], 'rval': [3, 4]})
right
Out[7]:
key rval
0 s1 3
1 s1 4
In [8]:
pd.merge(left, right, on='key')
Out[8]:
key lval rval
0 s1 1 3
1 s1 1 4
2 s1 2 3
3 s1 2 4

Another example that can be given is:

In [9]:
left = pd.DataFrame({'key': ['s1', 's2'], 'lval': [2, 3]})
left
Out[9]:
key lval
0 s1 2
1 s2 3
In [10]:
right = pd.DataFrame({'key': ['s1', 's2'], 'rval': [4, 5]})
right
Out[10]:
key rval
0 s1 4
1 s2 5
In [11]:
pd.merge(left, right, on='key')
Out[11]:
key lval rval
0 s1 2 4
1 s2 3 5

Append rows to a dataframe

In [12]:
df = pd.DataFrame(np.random.randn(4, 4), columns=['P', 'Q', 'R', 'S'])
df
Out[12]:
P Q R S
0 0.430829 1.429568 0.134299 0.392916
1 0.160762 0.327072 0.791582 0.596510
2 -0.226556 -1.800625 1.290731 1.592194
3 1.382239 0.110198 -0.634231 -0.673168
In [13]:
s = df.iloc[3]
In [15]:
df.append(s, ignore_index=True)
Out[15]:
P Q R S
0 0.430829 1.429568 0.134299 0.392916
1 0.160762 0.327072 0.791582 0.596510
2 -0.226556 -1.800625 1.290731 1.592194
3 1.382239 0.110198 -0.634231 -0.673168
4 1.382239 0.110198 -0.634231 -0.673168