selvam samymuthu
selvam samymuthu

Reputation: 63

Python-Pandas Join two columns by adding a character

There are three different columns, col2 and col3 need to be joined with the character "/" between the two columns and after joining column name need to be col2. please help !!!

col1  col2        col3
B     0.0.0.0 0   0    
B     2.145.26.0  24    
B     2.145.27.0  24    
B     10.0.0.0 8  20  

Expected output:

   col1   col2        
    B     0.0.0.0 0/0    
    B     2.145.26.0/24    
    B     2.145.27.0/24    
    B     10.0.0.0 8/20 

Upvotes: 0

Views: 1093

Answers (3)

iamanigeeit
iamanigeeit

Reputation: 834

df.col2 = df.col2.astype(str).str.cat(df.col3, sep='/')

See https://pandas.pydata.org/pandas-docs/version/0.23/api.html#string-handling for string operations.

Upvotes: 2

Samir Baid
Samir Baid

Reputation: 1178

Are you looking for something like this? Not sure if this can be labelled as Pythonic way?

temp_list = [{'col1':'B','col2':'0.0.0.0 0', 'col3':'0'}, 
         {'col1':'B','col2':'2.145.26.0', 'col3':'24'},
        {'col1':'B','col2':'2.145.27.0', 'col3':'24'},
        {'col1':'B','col2':'10.0.0.0 8', 'col3':'10'}]

df = pd.DataFrame(data=temp_list)

df['col4'] = df['col2'] + "/" + df['col3']

df.drop(columns=['col2','col3'],inplace=True)

df.rename(columns = {'col4':'col2'})

Upvotes: 1

BENY
BENY

Reputation: 323316

IIUC

df['col2']+='/'+df.col3.astype(str)
df
Out[74]: 
  col1           col2  col3
0    B     0.0.0.00/0     0
1    B  2.145.26.0/24    24
2    B  2.145.27.0/24    24
3    B   10.0.0.08/20    20

Upvotes: 2

Related Questions