pd.concat() is a function in the Pandas library that allows you to concatenate Pandas objects along a particular axis, either row-wise or column-wise.
Here's an example of how to use pd.concat() to concatenate two DataFrames vertically (i.e., along the rows):
import pandas as pd# create two DataFramesdf1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})df2 = pd.DataFrame({'A': [4, 5, 6], 'B': [7, 8, 9]})# concatenate the two DataFrames verticallyresult = pd.concat([df1, df2], ignore_index=True)print(result) |
Output:
A B0 1 41 2 52 3 63 4 74 5 85 6 9 |
In this example, we first create two DataFrames df1 and df2. We then use pd.concat() to concatenate them along the rows, using the syntax pd.concat([df1, df2], ignore_index=True). The ignore_index=True parameter tells Pandas to renumber the index of the resulting DataFrame, so that it starts from 0.
You can also concatenate DataFrames horizontally (i.e., along the columns) by setting the axis parameter to 1:
import pandas as pd# create two DataFramesdf1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})df2 = pd.DataFrame({'C': [7, 8, 9], 'D': [10, 11, 12]})# concatenate the two DataFrames horizontallyresult = pd.concat([df1, df2], axis=1)print(result) |
Output:
A B C D0 1 4 7 101 2 5 8 112 3 6 9 12 |
In this example, we create two DataFrames df1 and df2. We then use pd.concat() to concatenate them along the columns, using the syntax pd.concat([df1, df2], axis=1). The resulting DataFrame has four columns, with the columns from df1 on the left and the columns from df2 on the right.