连接字符串列和索引

Zub*_*ubo 2 python string concatenation dataframe pandas

我有一个DataFrame这样的:

A    B
----------
c    d
e    f
Run Code Online (Sandbox Code Playgroud)

我想引入第三列,由和索引串联而成,这样就变成ABDataFrame

A    B    C
---------------
c    d    cd0
e    f    ef1
Run Code Online (Sandbox Code Playgroud)

我想这样做:

df['C'] = df['A'] + df['B'] + # and here I don't know how to reference the row index. 
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

cs9*_*s95 5

选项 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
Run Code Online (Sandbox Code Playgroud)

或者,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
Run Code Online (Sandbox Code Playgroud)

选项 2
使用矢量化字符串连接的可扩展性较低的选项:

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

   A  B    C
0  c  d  cd0
1  e  f  ef1
Run Code Online (Sandbox Code Playgroud)

  • 美丽的。多谢! (2认同)