gpt-4.1-mini-2025-04-14· openai
from WildChat-4.8M
pd.concat two data frame horizontally
- User
pd.concat two data frame horizontally
- Assistant
To concatenate two pandas DataFrames horizontally (i.e., along the columns), you can use
pd.concatwith the argumentaxis=1.Here's a simple example:
pythonimport pandas as pd # Create two sample DataFrames df1 = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6] }) df2 = pd.DataFrame({ 'C': ['a', 'b', 'c'], 'D': ['d', 'e', 'f'] }) # Concatenate horizontally result = pd.concat([df1, df2], axis=1) print(result)Output:
codeA B C D 0 1 4 a d 1 2 5 b e 2 3 6 c fNotes:
- The default
axis=0concatenates vertically (rows). - Make sure the indices of the DataFrames align as expected (or reset/reindex as needed) to avoid unexpected NaN values in the result.
- To ignore the indices and create a default range index, you can use
ignore_index=Truebut this is seldom necessary for horizontal concatenation.
- The default