Python ProgrammingPython Programming

The following code demonstrates appending two DataFrame objects

Appending two DataFrame objects:

The set of columns of the DataFrame objects used in an append do not need to be the same. The resulting data frame will consist of the union of the columns in both, with missing column data filled with NaN.

import pandas as pd

df1 = pd.DataFrame({'Age': [30, 20, 22, 40], 'Height': [165, 70, 120, 80],
                    'Score': [4.6, 8.3, 9.0, 3.3], 'State': ['NY', 'TX',
                                                             'FL', 'AL']},
                   index=['Jane', 'Nick', 'Aaron', 'Penelope'])

df2 = pd.DataFrame({'Age': [32, 28, 39], 'Color': ['Gray', 'Black', 'Red'],
                    'Food': ['Cheese', 'Melon', 'Beans'],
                    'Score': [1.8, 9.5, 2.2], 'State': ['AK', 'TX', 'TX']},
                   index=['Dean', 'Christina', 'Cornelia'])

df3 = df1.append(df2, sort=True)

print(df3)


C:\python\pandas>python example20.py
           Age  Color    Food  Height  Score State
Jane        30    NaN     NaN   165.0    4.6    NY
Nick        20    NaN     NaN    70.0    8.3    TX
Aaron       22    NaN     NaN   120.0    9.0    FL
Penelope    40    NaN     NaN    80.0    3.3    AL
Dean        32   Gray  Cheese     NaN    1.8    AK
Christina   28  Black   Melon     NaN    9.5    TX
Cornelia    39    Red   Beans     NaN    2.2    TX
 
C:\python\pandas>