在遍历 URL 的列表之前重命名数据框列

Rename dataframe columns prior to looping through URL's list

我设置了一个代码来循环遍历链接的 XML 文件列表 (urls_list),展平文件并追加行。 我想重命名列,所以我在 cols 中设置了列名列表。 似乎行已正确附加到 df 中,但我不知道如何重命名列。

这是目前为止的代码:

import pandas as pd
import pandas_read_xml as pdx

urls_list = ['https://www.resultats-elections.interieur.gouv.fr/telechargements/PR2022/resultatsT1/027/058/058com.xml',
             'https://www.resultats-elections.interieur.gouv.fr/telechargements/PR2022/resultatsT1/084/007/007com.xml',
             'https://www.resultats-elections.interieur.gouv.fr/telechargements/PR2022/resultatsT1/032/062/062com.xml']

cols = ['type','annee','code_region','code_region_3','libelle_region','code_departement','code_min_departement','code_departement_3','libelle_departement','code_commune','libelle_commune','numero_tour',
        'nombre_inscrits','nombre_abstention','rapport_inscrits_abstention','nombre_votants','rapport_inscrits_votants','nombre_votes_blancs','rapport_inscrits_vote_blanc','rapport_votant_vote_blanc',
        'nombre_votes_nuls','rapport_inscrits_votes_nuls','rapport_votant_votes_nuls','nombre_exprimes','rapport_inscrits_exprimes','rapport_votant_exprimes','numero_panneau_candidat','nom','prenom','civilite',
        'nombre_de_voix','rapport_exprimes','rapport_inscrits']
df = []

for i in urls_list:
  data = pdx.read_xml(i)
  df.append(pdx.fully_flatten(data))

df_all = pd.DataFrame(df, columns=cols)

pandas 中有一个方法:.rename

文档中的代码示例:

df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})

df.rename(columns={"A": "a", "B": "c"})
   a  c
0  1  4
1  2  5
2  3  6

要在附加行后更改列名,必须创建包含所需列名的字典。

因此,对原始代码实施上述答案将得到:

urls_list = ['https://www.resultats-elections.interieur.gouv.fr/telechargements/PR2022/resultatsT1/027/058/058com.xml',
             'https://www.resultats-elections.interieur.gouv.fr/telechargements/PR2022/resultatsT1/084/007/007com.xml',
             'https://www.resultats-elections.interieur.gouv.fr/telechargements/PR2022/resultatsT1/032/062/062com.xml']

dfs = []

for i in urls_list:
  data = pdx.read_xml(i)
  dataframe = pdx.fully_flatten(data)
  dfs.append(dataframe)

df = pd.concat(dfs, ignore_index=True)

df = df.rename(columns={'A':'a','B':'b','C':'c'})