Union two pandas DataFrame
insights Stats
warning Please login first to view stats information.
Kontext
Code Snippets & Tips
Code snippets and tips for various programming languages/frameworks. All code examples are under MIT or Apache 2.0 license unless specified otherwise.
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)
copyright
This page is subject to Site terms.
comment Comments
No comments yet.