使用pandas DataFrame在新短语列中配置Concat 2列

时间:2019-05-16 18:00:56

标签: python pandas dataframe

我有一个这样的DataFrame:

>>> df = pd.DataFrame({'id_sin':['s123','s124','s125','s126','s127'],
                   'num1':[12,10,23,6,np.nan],
                   'num2':['BG','TC','AB','RC',np.nan],
                   'fr':[1,1,1,1,0],
})
>>> df
   fr id_sin  num1 num2
0   1   s123    12   BG
1   1   s124    10   TC
2   1   s125    23   AB
3   1   s126     6   RC
4   0   s127   NaN  NaN

我想用这样的短语连接num1num2 (num2是num1)列,其中fr为1:

   fr id_sin  num1 num2    phrase
0   1   s123    12   BG  BG is 12
1   1   s124    10   TC  TC is 10
2   1   s125    23   AB  AB is 23
3   1   s126     6   RC   RC is 6

我尝试了此方法,但不起作用:

df['phrase'] = str(df['num2']) + ' is ' + str(df['num1'])

1 个答案:

答案 0 :(得分:1)

修改
如果您希望num1没有小数点.0,请将其转换为Int64

df.num1 = df.num1.astype('Int64')

Out[32]:
  id_sin  num1 num2  fr
0   s123    12   BG   1
1   s124    10   TC   1
2   s125    23   AB   1
3   s126     6   RC   1
4   s127   NaN  NaN   0

尝试Series.str.cat

df.num2.str.cat(df.num1.astype(str), sep=' is ')

Out[2055]:
0    BG is 12
1    TC is 10
2    AB is 23
3     RC is 6
4         NaN
Name: num2, dtype: object

关于@rafael的评论。他的作品,只是其中的错字导致错误。是:

dn['num2'].astype(str) + ' is ' + dn['num1'].astype(str)