python - 用另一个数据框 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
解决方案
一种选择是列表理解:
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
推荐阅读
- javascript - 使用 jquery ajax、.net mvc 进行无限滚动
- java - 无法从静态上下文引用 Generis 方法出错
- angularjs - 力矩未定义角力矩选择器
- python - DjangOAuthToolkit - 如何为视图设置不同的读/写范围?
- cmake - CMake 3.11中带尖括号的美元是什么意思
- php - 如何在 Wordpress 中使用 AJAX 基于多个过滤器选择从数据库中获取数据
- sql-server - MSDTC 错误 - 调用 RpcMgmtInqServerPrincName 失败。合作伙伴不支持安全呼叫
- python-3.x - 检查表金字塔-SQLalchemy 中是否存在记录?
- informatica-powercenter - 关于唯一序列的 Informatica 场景
- java - 使用 Citrus Admin UI 创建项目时出错