Combining DataFrames

DataFrames can also be combined with each other, as long as they have the same number of entries along the combining axis. In this example, two DataFrames are concatenated vertically (for example, they contain the same number of columns, and their rows are stacked upon each other). DataFrames can also be concatenated horizontally (if they contain the same number of rows) by specifying the axis parameter. Note that the column names and row names should correspond to each other across the DataFrames; if they do not, new columns will be formed and NaN values will be inserted for any missing values.

First, we create a new DataFrame name, df2:

df2 = pd.DataFrame({
'col3': ['a', 'b', 'c', 'd'],
'new_col1': '',
'new_col2': 0,
'new_col3': [11, 13, 15, 17],
'new_col4': [17, 19, 21, 23],
'new_col5': [7.5, 8.5, 9.5, 10.5],
'new_col6': [13, 14, 15, 16]
});
print(df2)

The output is as follows:

  col3 new_col1  new_col2  new_col3  new_col4  new_col5  new_col6
0    a                  0        11        17       7.5        13
1    b                  0        13        19       8.5        14
2    c                  0        15        21       9.5        15
3    d                  0        17        23      10.5        16

Next, we perform the concatenation. We set the optional ignore_index argument equal to True to avoid duplicate row indices:

df3 = pd.concat([df, df2] ignore_index = True)
print(df3)

The output is as follows:

  col3 new_col1  new_col2  new_col3  new_col4  new_col5  new_col6
0    x                  0         5         5       7.0        10
1    y                  0         7         7       8.0        11
2    z                  0         9         9       9.0        12
3    a                  0        11        17       7.5        13
4    b                  0        13        19       8.5        14
5    c                  0        15        21       9.5        15
6    d                  0        17        23      10.5        16
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset