Concatenating DataFrames in Pandas

Concatenating DataFrames in pandas is like building a Lego structure-snapping pieces together to form something bigger and better. Let’s build.

Straightforward Concatenation

Concatenating allows you to combine multiple DataFrames vertically or horizontally, expanding your dataset seamlessly:

import pandas as pd

# Sample DataFrames
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df2 = pd.DataFrame({'A': [7, 8, 9], 'B': [10, 11, 12]})

# Concatenate DataFrames vertically
concatenated_df = pd.concat([df1, df2], axis=0)
print(concatenated_df)

This example stacks df1 and df2 vertically, effectively doubling the number of rows while keeping the same columns.

Snapping together pieces of data with concatenation in pandas allows for quick and efficient data assembly, setting the stage for deeper analysis and insights.

Leave a Reply