Ben Chuanlong Du's Blog

It is never too late to learn.

Reshape a pandas DataFrame

Reshape DataFrame

In [9]:
import pandas as pd
import numpy as np
In [10]:
df1 = pd.DataFrame({"x": [1, 2, 3], "y": [5, 4, 3]})
df1
Out[10]:
x y
0 1 5
1 2 4
2 3 3
In [3]:
df2 = pd.DataFrame({"x": [0, 0, 3000], "y": [78, 4, 3]})
df2
Out[3]:
x y
0 0 78
1 0 4
2 3000 3

Concate Rows

You can use both the DataFrame.append (returns a new data frame rather than in-place) and pandas.concat to concate rows of data frames. pandas.concat is recommended when you want to concate rows of multiple data frames.

In [4]:
df1.append(df2, ignore_index=True)
Out[4]:
x y
0 1 5
1 2 4
2 3 3
3 0 78
4 0 4
5 3000 3
In [5]:
df1
Out[5]:
x y
0 1 5
1 2 4
2 3 3
In [6]:
pd.concat([df1, df2], ignore_index=True)
Out[6]:
x y
0 1 5
1 2 4
2 3 3
3 0 78
4 0 4
5 3000 3

Repeat rows of a DataFrame.

In [11]:
pd.concat([df1] * 3, ignore_index=True)
Out[11]:
x y
0 1 5
1 2 4
2 3 3
3 1 5
4 2 4
5 3 3
6 1 5
7 2 4
8 3 3

Concate Columns

In [7]:
pd.concat([df1, df2], axis=1)
Out[7]:
x y x y
0 1 5 0 78
1 2 4 0 4
2 3 3 3000 3
In [8]:
pd.concat([df1, df2], ignore_index=True, axis=1)
Out[8]:
0 1 2 3
0 1 5 0 78
1 2 4 0 4
2 3 3 3000 3
In [ ]:
 

Comments