Combine two columns of text in Pandas DataFrame

In this tutorial, we will learn how to combine two columns of text in Pandas DataFrame with the help of example? By Pranit Sharma Last updated : April 12, 2023

Combine DataFrame's Two Text Columns

To combine two columns of text in Pandas DataFrame, use pandas.Series.str.cat() method. It is used for concatenating two or more strings. It takes the value of a particular column as an input along with the value of another column which has to be combined.

Syntax

df['new_col_name'] = df['col_1_name'].str.cat(df['col_2_name']) 

The method takes a parameter sep, where sep means separator, it is the special character that comes between the combined strings.

Let us understand with the help of an example.

Example to Combine two columns of text in Pandas DataFrame

# Importing pandas package
import pandas as pd

# Creating a dictionary of student marks
d = {
    "Name":['Hari','Mohan','Neeti','Shaily'],
    "Age":[25,36,26,21],
    "Gender":['Male','Male','Female','Female'],
    "Profession":['Doctor','Teacher','Singer','Student'],
    "Title":['Mr','Mr','Ms','Ms']
}

# Now, Create DataFrame
df = pd.DataFrame(d)

# Printing the original DataFrame
print("Original DataFrame:\n")
print(df,"\n\n")

# Now, Combine the values of Name and 
# title using str.cat() function
df['Full_Name'] = df['Title'].str.cat(df['Name'], sep =".")

# Now, Printing the modified DataFrame
print("Combined column:\n")
print(df)

Output

Original DataFrame:

     Name  Age  Gender Profession Title
0    Hari   25    Male     Doctor    Mr
1   Mohan   36    Male    Teacher    Mr
2   Neeti   26  Female     Singer    Ms
3  Shaily   21  Female    Student    Ms 


Combined column:

     Name  Age  Gender Profession Title  Full_Name
0    Hari   25    Male     Doctor    Mr    Mr.Hari
1   Mohan   36    Male    Teacher    Mr   Mr.Mohan
2   Neeti   26  Female     Singer    Ms   Ms.Neeti
3  Shaily   21  Female    Student    Ms  Ms.Shaily

Output (Screenshot)

Combine two columns | Output

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.