首页 > 解决方案 > 用另一个数据框 pandas 重命名每 2 列

问题描述

我有 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

标签: pythonpandasnumpy

解决方案


一种选择是列表理解:

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

推荐阅读