In data analysis and manipulation, it is common to combine or concatenate multiple tables to create a single data structure for analysis. Pandas, a popular Python library for data manipulation and analysis, provides a concat()
function that allows you to combine tables either horizontally or vertically. In this article, we will demonstrate how to use the concat()
function in pandas to concatenate tables horizontally and vertically.
Horizontal concatenation involves merging two tables by columns, effectively extending the tables by columns. This can be achieved using the concat()
function in pandas by setting the axis
parameter to 1
.
import pandas as pd
# Create two DataFrames
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']})
df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
'B': ['B4', 'B5', 'B6', 'B7'],
'C': ['C4', 'C5', 'C6', 'C7'],
'D': ['D4', 'D5', 'D6', 'D7']})
# Merge the two tables horizontally.
result = pd.concat([df1, df2], axis=1)
print(result)
Vertical concatenation involves stacking tables on top of each other, effectively extending the tables by rows. This can be achieved using the concat()
function in pandas by setting the axis
parameter to 0
.
import pandas as pd
# Create two DataFrames
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']})
df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
'B': ['B4', 'B5', 'B6', 'B7'],
'C': ['C4', 'C5', 'C6', 'C7'],
'D': ['D4', 'D5', 'D6', 'D7']})
# Concatenate the two tables vertically
result = pd.concat([df1, df2], axis=0)
print(result)
In this article, we have discussed how to use the concat()
function in the pandas library to concatenate tables horizontally or vertically by specifying the axis
parameter. By following the examples provided in this article, you should be able to effectively merge tables to create a single, comprehensive dataset for further data analysis and manipulation. Happy coding!
Thank you for taking the time to explore data-related insights with me. I appreciate your engagement. If you find this information helpful, I invite you to follow me or connect with me on LinkedIn or X(@Luca_DataTeam). You can also catch glimpses of my personal life on Instagram, Happy exploring!👋