首页 > 解决方案 > 如何将列表与数据框列标题进行比较并替换标题的名称?

问题描述

有一个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 方法并不是我真正需要的

感谢任何帮助

标签: pythonpandaslist

解决方案


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

推荐阅读