Union two pandas DataFrame

Kontext Kontext 0 236 0.34 index 8/9/2023

Code description

This code snippet shows you how to union two pandas DataFrames in python using concat method in pandas namespace.If the schema is different, pandas will autmatically merge it.

Output

      category  value  user
    0        A      0   2.0
    1        B      1   3.0
    2        C      2   2.0
    3        D      3   1.0
    4        E      4   1.0
    0        A      0   NaN
    1        B      1   NaN
    2        C      2   NaN
    3        D      3   NaN
    4        E      4   NaN

For the second DataFrame, column user doesn't exist. Pandas uses  NaN to mark it.

Code snippet

    import pandas as pd
    import random
    
    categories = []
    users = []
    values = []
    for i in range(0, 5):
        categories.append(chr(i % 10+65))
        values.append(i)
        users.append(random.randint(1, 10))
    
    df1 = pd.DataFrame({'category': categories, 'value': values, 'user': users})
    
    df2 = pd.DataFrame({'category': categories, 'value': values})
    
    df = pd.concat([df1, df2])
    
    print(df)
pandas python

Join the Discussion

View or add your thoughts below

Comments