我设置了一个代码,循环遍历链接的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)发布于 2022-04-19 11:02:40
熊猫有一种这样的方法:.rename
来自docu的代码示例:
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发布于 2022-04-19 12:28:19
若要在附加行后更改列名,必须创建具有所需列名的字典。
因此,实现上述对原始代码的答案将提供:
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'})https://stackoverflow.com/questions/71923824
复制相似问题