Stack Exchange
create column concatenating strings
I have this dataframe:
import pandas as pd

df = pd.DataFrame({'type':['HEPA2', 'HEPA3'], 
                   'dep': ['B01', 'C02'],
                   'c': [1 ,2],
                   'ch':[3, 4]})

df.dtypes:
type    object
dep     object
c        int64
ch       int64
dtype: object

and I want to create a new column where I concatenate some strings:
df['name'] = str(str(df['dep']) + '-' + 'c' + str(df['c']) + '-' + str(df['ch']))

and df is:
        type    dep     c   ch  name
0      HEPA2    B01     1   3   0 B01\n1 C02\nName: dep, dtype: object-c...
1      HEPA3    C02     2   4   0 B01\n1 C02\nName: dep, dtype: object-c...

instead of:
       type     dep     c      ch   name
0       HEPA2   B01     1      3     B01-1-3
1       HEPA3   C02     2      4     C02-2-4


Instead of str() you should use df['column'].astype(str)
df['name'] = df['dep'] + '-' + df['c'].astype(str) + '-' + df['ch'].astype(str)


Use agg and join on columns dep, c, ch and assign back to column name as follows
df['name'] = df.drop('type', 1).astype(str).agg('-'.join, axis=1)


Out[331]:
    type  dep  c  ch     name
0  HEPA2  B01  1   3  B01-1-3
1  HEPA3  C02  2   4  C02-2-4


another alternative:
df['name'] = df.apply(lambda x: '{}-{}-{}'.format(x['dep'], x['c'], x['ch']), axis=1)

Output:
    type  dep  c  ch     name
0  HEPA2  B01  1   3  B01-1-3
1  HEPA3  C02  2   4  C02-2-4


Instead of using str() use .str method and .cat() to concatenate:
In [16]: df['dep'].str.cat(df['c'].astype('str'),sep='-').str.cat(df['ch'].astype('str'), sep='-')
Out[16]:
0    B01-1-3
1    C02-2-4
Name: type, dtype: object

