连接字符串列和索引

时间:2018-03-14 20:59:28

标签: python string pandas dataframe concatenation

我有DataFrame这样:

A    B
----------
c    d
e    f

我想介绍第三列,由AB和索引的串联组成,以便DataFrame成为:

A    B    C
---------------
c    d    cd0
e    f    ef1

我想这样做:

df['C'] = df['A'] + df['B'] + # and here I don't know how to reference the row index. 

我该怎么做?

3 个答案:

答案 0 :(得分:3)

选项1
为了获得更好的可扩展性,请使用assign + agg

df['C'] = df.assign(index=df.index.astype(str)).agg(''.join, 1)
df

   A  B    C
0  c  d  cd0
1  e  f  ef1

或者,以类似的方式使用np.add.reduce

df['C'] = np.add.reduce(df.assign(index=df.index.astype(str)), axis=1)
df

   A  B    C
0  c  d  cd0
1  e  f  ef1

选项2
使用矢量化字符串连接的可伸缩性较小的选项:

df['C'] = df['A'] + df['B'] + df.index.astype(str)
df

   A  B    C
0  c  d  cd0
1  e  f  ef1

答案 1 :(得分:1)

pd.DataFrame.itertuples
Python 3.6

df.assign(C=[f'{a}{b}{i}' for i, a, b in df.itertuples()])

   A  B    C
0  c  d  cd0
1  e  f  ef1

使用pd.Series.str.cat

df.assign(C=df.A.str.cat(df.B).str.cat(df.index.astype(str)))

   A  B    C
0  c  d  cd0
1  e  f  ef1

Mish / Mash

from operator import add
from functools import reduce
from itertools import chain

df.assign(C=reduce(add, chain((df[c] for c in df), [df.index.astype(str)])))

   A  B    C
0  c  d  cd0
1  e  f  ef1

求和

df.assign(C=df.sum(1) + df.index.astype(str))

   A  B    C
0  c  d  cd0
1  e  f  ef1

答案 2 :(得分:0)

df['C'] = df['A'].astype(str) + df['B'].astype(str) + np.array(map(str, df.index.values))

基本上你用df.index访问df索引,并把它变成一个numpy数组你添加.values,并将它转换成一个字符串(以便轻松添加到以前的列,这是字符串),你可以使用地图功能。

编辑:将.astype(str)添加到A列和B列,将它们转换为字符串。如果它们已经是字符串,那么这将是必要的。