创建列连接字符串

时间:2019-07-03 08:36:58

标签: python-3.x pandas

我有这个数据框:

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

,我想在其中连接一些字符串的地方创建一个新列:

df['name'] = str(str(df['dep']) + '-' + 'c' + str(df['c']) + '-' + str(df['ch']))

和df是:

        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...

代替:

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

4 个答案:

答案 0 :(得分:1)

您应该使用str()代替df['column'].astype(str)

df['name'] = df['dep'] + '-' + df['c'].astype(str) + '-' + df['ch'].astype(str)

答案 1 :(得分:0)

aggjoindep列上使用cch,并按如下所示分配回列name

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

答案 2 :(得分:0)

另一种选择:

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

输出:

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

答案 3 :(得分:0)

不是使用str()而是使用.str方法和.cat()进行连接:

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