How to combine two text columns in pandas

Spread the love

Problem –

You have two text columns in pandas and you want to combine them into a single column.

Solution –

import pandas as pd
url = ""
df = pd.read_csv(url)

Let’s say that you want to add the gender and marital status columns into one column. Since both the columns are string, you can concatenate them directly.

df['Gender'] + '_' + df['Marital Status']

To make it more readable, I have added an white space between them.

Now, suppose one column is string but the other one is a integer. Now how do you add that?

To add these columns you have to first convert the integer column into a string using astype method in pandas.

let’s add the Age and gender column.

df['Gender'] + ' ' + df['Age'].astype(str)

If you want to add more than two columns at once, then use the same method that we used so far.

df['Gender'] + ' ' + df['Marital Status'] + ' ' + df['Age'].astype(str)

1 . Pandas – astype() – Change column data type in pandas

Rating: 1 out of 5.

Leave a Reply