MLP FU
Pandas

Concatenating DataFrames

Concatenation is the process of stacking multiple DataFrames along an axis. The pd.concat() function is used for this purpose.

Basic Concatenation

By default, pd.concat() stacks DataFrames vertically (axis=0).

import pandas as pd
df1 = pd.DataFrame({'A': ['A0', 'A1'], 'B': ['B0', 'B1']})
df2 = pd.DataFrame({'A': ['A2', 'A3'], 'B': ['B2', 'B3']})
df3 = pd.DataFrame({'A': ['A4', 'A5'], 'B': ['B4', 'B5']})

result = pd.concat([df1, df2, df3])
print(result)

Notice that the index is preserved. If you want a new index, you can use the ignore_index=True parameter.

import pandas as pd
df1 = pd.DataFrame({'A': ['A0', 'A1'], 'B': ['B0', 'B1']})
df2 = pd.DataFrame({'A': ['A2', 'A3'], 'B': ['B2', 'B3']})
result = pd.concat([df1, df2], ignore_index=True)
print(result)

Concatenating Horizontally

You can concatenate DataFrames horizontally by setting axis=1. This is similar to a SQL join.

import pandas as pd
df1 = pd.DataFrame({'A': ['A0', 'A1'], 'B': ['B0', 'B1']})
df2 = pd.DataFrame({'C': ['C0', 'C1'], 'D': ['D0', 'D1']})
result = pd.concat([df1, df2], axis=1)
print(result)