如何将列表与dataframe列标题进行比较并替换标题的名称?

2024-04-26 00:30:03 发布

您现在位置: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 column)匹配

sql_table (as df) = 

column_name   column_id
city          0
street        1
house         2
flat          3

我需要用sql_表中的列ID替换df_示例中的列名

像这样


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

谢谢你的帮助


Tags: idstreetcitydfexamplecolumnsfla
1条回答
网友
1楼 · 发布于 2024-04-26 00:30:03

renamezip创建的词典一起使用:

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

相关问题 更多 >