使用其他数据框熊猫中的每两列重命名

我有2个示例数据帧:

df1 = 

a_1  b_1  a_2  b_2
  1    2    3    4
  5    6    7    8

df2 = 

 c    
12
14

我想按顺序添加c的值作为后缀:

df3 = 

12_a_1  12_b_1  14_a_2  14_b_2
     1       2       3       4
     5       6       7       8
axingweb 回答:使用其他数据框熊猫中的每两列重命名

一个选项是列表理解:

import itertools
# use itertools to repeat values of df2
prefix = list(itertools.chain.from_iterable(itertools.repeat(str(x),2) for x in df2['c'].values))

# list comprehension to create new column names
df1.columns = [p+'_'+c for c,p in zip(df1.columns,prefix)]
print(df1)

   12_a_1  12_b_1  14_a_2  14_b_2
0       1       2       3       4
1       5       6       7       8
,

使用str.splitmap

s = (df1.columns.str.split('_').str[-1].astype(int) - 1).map(df2.c)
df1.columns = s.astype(str) + '_' + df1.columns
print(df1)

Out[304]:
   12_a_1  12_b_1  14_a_2  14_b_2
0       1       2       3       4
1       5       6       7       8
本文链接:https://www.f2er.com/3169722.html

大家都在问