Pandas Pandas Concatenate Columns a Comprehensive Guide

o concatenate columns in Pandas, you can use the concat function or the + operator. Here are some examples:

Using concat:

Suppose you have a DataFrame df with two columns, col1 and col2, and you want to concatenate them into a new column concat_col.

import pandas as pd

df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})

df['concat_col'] = pd.concat([df['col1'], df['col2']], axis=1)

print(df)

Output:

   col1  col2  concat_col
0     1     4           1
1     2     5           2
2     3     6           3

Using + operator:

Alternatively, you can use the + operator to concatenate the columns:

df['concat_col'] = df['col1'].astype(str) + df['col2'].astype(str)

print(df)

Output:

   col1  col2 concat_col
0     1     4         14
1     2     5         25
2     3     6         36

Note that in this case we first convert the columns to string using the astype method so that the concatenation is done as string concatenation, rather than numerical addition.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *