Q:

Combine two columns of text in Pandas DataFrame

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

Combine two columns | Output

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now