Python | Pandas Series.str.cat () to concatenate strings

Pandas str.cat() is used to concatenate strings into a passed sequence of calling strings. Individual values ​​from another series can be transferred, but the length of both series must be the same.  must be prefixed to distinguish it from the default Python method.

Syntax: Series.str.cat (others = None, sep = None, na_rep = None)

Parameters:
others: Series, index, data frame or list of strings to concatenate
sep : Separator to be put between the two strings
na_rep: None or string value to replace in place of null values ​​

Return type: Series with concatenated string valus

To download the CSV file in use, click here.

In the following examples, the data frame used contains data about some NBA players. An image of the data frame before any operations is attached below. 

Example # 1: delimited join column

This example concatenates the Command column at the end of the Name column with the delimiter “,“. The Name column is overwritten by the new series and then the data frame is displayed.

# pandas module import

import pandas as pd

  
# CSV import by link

data = pd.read_csv ( " https://media.python.engineering/wp-content/uploads/nba.csv " )

 
# create a copy of the command column

new = data [ " Team " ]. Copy ()

  
# combine command with column name
# overwrite column name

data [ " Name " ] = data [ "Name" ]. str . cat (new, sep = "," )

 
# display
data

Output:
As shown in the output image, each row in the Team column that has the same index as the row in the Name column has been concatenated with the delimiter “,“. 

Example # 2: Handling null values ​​

The most important part of data analysis is handling null values. str.cat () provides a way to handle null values ​​using the na_rep parameter. Anything passed to this parameter will be replaced each time a null value occurs. 
This example combines the college column with the team column. “No college” is passed to the na_rep parameter to replace zero with this string.

# pandas module import

import pandas as pd

 
# CSV import by link

data = pd.read_csv ( " https://media.python.engineering/wp-content/uploads/nba.csv " )

 
# create a copy of the command column

new = data [ " Team " ]. copy ()

  
# string to replace empty values ​​

na_string = "No College"

 
# concatenate command with column name
# overwrite column name

data [ "College" ] = data [ "College" ]. str . cat (new, sep = "," , na_rep = na_string)

  
< code class = "comments"> # display

data

Output:
As you can see from the data frame, there was a NULL value at positions 4 and 5 of the index, which was replaced with “No college “, And the row from the” Command “column was successfully merged.