Kontext Kontext

Union two pandas DataFrame

event 2023-08-09 visibility 140 comment 0 insights
more_vert
insights Stats

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)
More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts