Concatenate Column Values in Pandas DataFrame

Sometimes you need to concatenate column values in your Pandas DataFrame to create a new unique column (uid = unique id), so you can do a look-up value from another DataFrame.

From the below example you will have 4 original columns: MRBTS, LNBTS, LNCEL, and dlChBw, and then add a new column ‘UID’ by concatenating the value of MRBTS, LNBTS, and LNCEL columns:

Script:

import pandas as pd

data = {
    'MRBTS': [523736, 523736, 523736, 523736, 523736], 
    'LNBTS': [523736, 523736, 523736, 523736, 523736], 
    'LNCEL': [1, 14, 15, 16, 17], 
    'dlChBw': [50, 200, 200, 200, 150], 
}

# Original Pandas DataFrame
df = pd.DataFrame(data)
print(df, end='\n\n')

# Simple Concatenate
df['UID_Simple'] = df['MRBTS'].map(str) + "-" + df['LNBTS'].map(str) + "-" + df['LNCEL'].map(str)
print(df, end='\n\n')

# Concatenate with Prefix
df['UID'] = df['MRBTS'].apply(lambda x: "PLMN-PLMN/MRBTS-{}".format(x)) + df['LNBTS'].apply(lambda x: "/LNBTS-{}".format(x)) + df['LNCEL'].apply(lambda x: "/LNCEL-{}".format(x))
print(df)

From the script above you can “Concatenate Column Values with or without Prefix”.

Output:

concatenate_column_values_with_and_without_prefix

Leave a comment