将普通数据转换为时间序列数据帧 panda Python

时间:2021-01-28 08:15:59

标签: python pandas dataframe numpy google-colaboratory

我有一个关于将数据转换为时间序列的小问题。这是我执行的步骤。 我的输出数据如下: Beautiful Soup 是一个可以轻松从网页中抓取信息的库。它位于 HTML 或 XML 解析器之上,为迭代、搜索和修改解析树提供 Pythonic 习惯用法。

url1 = 'http://financials.morningstar.com/finan/financials/getFinancePart.html?&callback=xxx&t=BBRI'
url2 = 'http://financials.morningstar.com/finan/financials/getKeyStatPart.html?&callback=xxx&t=BBRI'

soup1 = BeautifulSoup(json.loads(re.findall(r'xxx\((.*)\)', requests.get(url1).text)[0])['componentData'], 'lxml')
soup2 = BeautifulSoup(json.loads(re.findall(r'xxx\((.*)\)', requests.get(url2).text)[0])['componentData'], 'lxml')

def print_table(soup):
    for i, tr in enumerate(soup.select('tr')):
        row_data = [td.text for td in tr.select('th, td') if td.text]
        if not row_data:
            continue
        if len(row_data) < 12:
            row_data = ['X'] + row_data
        for j, td in enumerate(row_data):
            if j==0:
                print('{: >30}'.format(td))
            else:
                print('{: ^12}'.format(td))
        print()


print_table(soup1)

产生输出

          X
  2010-12   
  2011-12   
  2012-12   
  2013-12   
  2014-12   
  2015-12   
  2016-12   
  2017-12   
  2018-12   
  2019-12   
    TTM     

               Revenue IDR Mil
 30,552,600 
 40,203,051 
 43,104,711 
 51,133,344 
 59,556,636 
 69,813,152 
 82,504,537 
 90,844,308 
 99,067,098 
108,468,320 
105,847,159 

我需要将它转换为一个数据框,panda 是:

data

   X        Revenue IDR Mil
  2010-12        30,552,600 
  2011-12        40,203,051 
  2012-12        43,104,711
  2013-12        51,133,344    
  2014-12        59,556,636    
  2015-12        69,813,152  
  2016-12        82,504,537   
  2017-12        90,844,308 
  2018-12        99,067,098   
  2019-12        108,468,320   
  2020-12        105,847,159     

1 个答案:

答案 0 :(得分:0)

这与您正在做的事情相比略有简化,但我认为它可以让您找到需要的地方,主要来自Bitto Bennichan

import json
import pandas as pd

url1 = 'http://financials.morningstar.com/finan/financials/getFinancePart.html?t=BBRI'
url2 = 'http://financials.morningstar.com/finan/financials/getKeyStatPart.html?t=BBRI'

lm_json = requests.get(url1).json()
df_list=pd.read_html(lm_json["componentData"])
df_list[0].transpose()