【问题标题】:From XML url to Pandas dataframe从 XML url 到 Pandas 数据框
【发布时间】:2021-09-14 04:28:06
【问题描述】:

我是 Python 新手,在从 Web 导入一个简单的 XML 文件并将其转换为 pandas DF 时遇到了一些问题: https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/cny.xml

我尝试了几种方法,包括使用 BS4,但都没有成功。

from bs4 import BeautifulSoup
import requests
socket = requests.get('https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/cny.xml')
soup = bs4.BeautifulSoup(socket.content, ['lxml', 'xml'])

all_obs = soup.find_all('Obs')

l = []
df = pd.DataFrame(columns=['TIME_PERIOD','OBS_VALUE'])
pos= 0
for obs in all_obs:
    l.append(obs.find('TIME_PERIOD').text)
    l.append(obs.find('OBS_VALUE').text)
    


    df.loc[pos] = l
    l = []
    pos+=1
    
print(df)

有人可以帮我吗? 谢谢

【问题讨论】:

    标签: python python-3.x pandas xml xml-parsing


    【解决方案1】:

    哎呀!

    from bs4 import BeautifulSoup
    import requests
    import pandas as pd
    
    response = requests.get('https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/cny.xml')
    
    bs = BeautifulSoup(response.text, ['xml'])
    
    obs = bs.find_all("Obs")
    #<Obs OBS_CONF="F" OBS_STATUS="A" OBS_VALUE="10.7255" TIME_PERIOD="2005-04-01"/>
    
    df = pd.DataFrame(columns=['TIME_PERIOD','OBS_VALUE'])
    
    for node in obs:
        df = df.append({'TIME_PERIOD': node.get("TIME_PERIOD"), 'OBS_VALUE': node.get("OBS_VALUE")}, ignore_index=True)
        
    df.head()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-22
      • 2020-11-14
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      • 2019-11-05
      相关资源
      最近更新 更多