我設定了一個代碼來遍歷鏈接的 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)
uj5u.com熱心網友回復:
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
uj5u.com熱心網友回復:
要在附加行后更改列名,必須創建一個包含所需列名的字典。
因此,對原始代碼實施上述答案將給出:
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://www.uj5u.com/qukuanlian/458768.html
上一篇:Concat2資料幀并洗掉重復項 考慮將NaN值替換為來自其中一個資料幀的資料的日期和時間
下一篇:在條件下按列分組以計算平均值
