Home »
Python »
Python Programs
Combine two columns of text in Pandas DataFrame
Given a DataFrame, we have to combine the text of two columns.
Submitted by Pranit Sharma, on April 13, 2022
Columns are the different fields that contains their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. Sometimes, we might need to combine the text of two columns. Pandas allows us to achieve this task using the cat() function.
pandas.Series.str.cat() Method
The cat is the short form for concatenation. The cat() method 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'])
Parameters: It takes a parameter sep, where sep means separator, it is the special character that comes between the combined strings.
To work with Python Pandas, we need to import the pandas library. Below is the syntax,
import pandas as pd
Let us understand with the help of an example.
Example:
# 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
Python Pandas Programs »