Concatenating two columns of the dataframe in pandas can be easily achieved by using simple ‘+’ operator . Let’s see how to
- Concatenate two columns of dataframe in pandas (two string columns)
- Concatenate integer (numeric) and string column of dataframe in pandas python
Let’s first create the dataframe.
import pandas as pd import numpy as np #Create a DataFrame df1 = { 'State':['Arizona','Georgia','Newyork','Indiana','Florida'], 'State_code':['AZ','GG','NY','IN','SL'], 'Score':[62,47,55,74,31]} df1 = pd.DataFrame(df1,columns=['State','State_code','Score']) print(df1)
So the resultant dataframe will be
Concatenate two string columns pandas:
Let’s concatenate two columns of dataframe with ‘+’ as shown below
df1['state_and_code'] = df1['State'] + df1['State_code'] print(df1)
So the result will be
Concatenate two string columns with space in pandas:
Let’s concatenate two columns of dataframe with space as shown below
df1['state_and_code'] = df1['State'] +' '+ df1['State_code'] print(df1)
So the result will be
Concatenate two string columns with – (hyphen) in pandas:
Let’s concatenate two columns of dataframe with – (hyphen) as shown below
df1['state_and_code'] = df1['State'] +'-'+ df1['State_code'] print(df1)
So the result will be
Concatenate String and numeric column in pandas:
First we need to convert integer column to string column using map(str) function and then concatenate as shown below
df1['code_and_score'] = df1["State_code"]+ "-" + df1["Score"].map(str) print(df1)
So the resultant dataframe will be