python - 如何将列表与数据框列标题进行比较并替换标题的名称?
问题描述
有一个df
df_example =
id city street house flat
0 NY street_ny 111 01
1 LA street_la 222 02
2 SF street_sf 333 03
3 Vegas street_vg 444 04
4 Boston street_bs 555 05
并且在数据库中存在一个表,其中每个列名都与列 id 匹配(withoit id 列)
sql_table (as df) =
column_name column_id
city 0
street 1
house 2
flat 3
我需要用 sql_table 中的列 ID 替换 df_example 列名
像这样
id 0 1 2 3
0 NY street_ny 111 01
1 LA street_la 222 02
2 SF street_sf 333 03
3 Vegas street_vg 444 04
4 Boston street_bs 555 05
到目前为止,我得到了没有 id 列名的列名列表
column_names_list = list(df_example)[1:]
column_names_list = ['city', 'street', 'house', 'flat']
但是如何进行我不知道
.isin 方法并不是我真正需要的
感谢任何帮助
解决方案
rename
与由创建的字典一起使用zip
:
df_example = df_example.rename(columns=dict(zip(df['column_name'], df['column_id'])))
print (df_example)
id 0 1 2 3
0 0 NY street_ny 111 1
1 1 LA street_la 222 2
2 2 SF street_sf 333 3
3 3 Vegas street_vg 444 4
4 4 Boston street_bs 555 5
推荐阅读
- java - 无法通过 IntelliJ Idea 和 Gradle 使用构建文件夹中生成的类
- python - Pyspark - 如何检查两条记录中哪一条具有最新日期及其列值?
- c# - 模糊输入系统.反射
- python - 试图在 tkinter 中设置标签文本
- ruby-on-rails - 条纹和重定向导致 Heroku 上的错误
- office-js - 提交 Office 插件时“附加服务或帐户披露”失败
- javascript - 如何在单击同一tr的td内的按钮时防止单击tr
- powershell - Powershell WebRequest 每次都会给出不同的响应
- asp.net-core - 将 MiniProfiler 与 .NetCore 3.1 集成
- f# - 如何命名中缀运算符?