Using concat to Stack DataFrames Vertically
If the two DataFrames have the same columns and you want to stack them vertically, you can use the pd.concat
method:
import pandas as pd # Define the first DataFrame df1 = pd.DataFrame({ 'Name': ['Alice', 'Bob'], 'Age': [25, 30], 'City': ['New York', 'Los Angeles'] }) # Define the second DataFrame df2 = pd.DataFrame({ 'Name': ['Charlie', 'David'], 'Age': [35, 40], 'City': ['Chicago', 'Houston'] }) # Concatenate the two DataFrames result = pd.concat([df1, df2]) # Print the result print(result)
Using merge to Join DataFrames Horizontally
If you want to join two DataFrames based on a common column (for example, an ID), you can use the pd.merge
method:
# Define the first DataFrame df1 = pd.DataFrame({ 'ID': [1, 2], 'Name': ['Alice', 'Bob'] }) # Define the second DataFrame df2 = pd.DataFrame({ 'ID': [1, 2], 'Age': [25, 30] }) # Merge the two DataFrames on the 'ID' column result = pd.merge(df1, df2, on='ID') # Print the result print(result)