Python - append in the same Dataframe

Asked

Viewed 25 times

1

I have the following code to extract data from the yahoo that works perfectly. My problem is that I wanted to insert all the data into a single table every time it enters the FOR it go add to the table but I’m not getting.

Thanks for your help so far.

for codigo_acao in acoes_ibov["Papel"]:
print("Acessando informações da ação: ",codigo_acao)



url = "https://br.financas.yahoo.com/quote/"+ codigo_acao +".SA/history?period1=1170288000&period2=4117305600&interval=div%7Csplit&filter=div&frequency=1d&includeAdjustedClose=true"

header = {
  "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
  "X-Requested-With": "XMLHttpRequest"
}

r = requests.get(url, headers=header)


acao = pd.read_html(r.text ,decimal = ",", thousands = "." )

acao = acao[0].iloc[1:-1,:2]

informacoes_1= acao.insert(loc= 0,column="Papel",value=codigo_acao)
print("Informações")
display(acao)

1 answer

0


You can use the pandas append, in which case a new data frame was created to go adding the results to it:

import pandas as pd
import requests

header = {
      "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
      "X-Requested-With": "XMLHttpRequest"
}

# novo data frame
df = pd.DataFrame(columns=['Papel','Símbolo','Nome'])

acoes_ibov = ['AAPL','FB']

for codigo_acao in acoes_ibov:
    print("Acessando informações da ação: ", codigo_acao)

    url = "https://br.financas.yahoo.com/quote/"+ codigo_acao +".SA/history?period1=1170288000&period2=4117305600&interval=div%7Csplit&filter=div&frequency=1d&includeAdjustedClose=true"

    r = requests.get(url, headers=header)

    acao = pd.read_html(r.text ,decimal = ",", thousands = "." )
    acao = acao[0].iloc[1:-1,:2]
    acao.insert(loc=0, column="Papel", value=codigo_acao)
    df = df.append(acao)
    
display(df.head())

I placed the shares because you did not provide.

  • 1

    Thank you very much my dear, I did not put the actions why I caught her from a csv. But your answer helped me a lot to solve this problem!

  • 1

    @Doom for nothing! Glad you solved the problem! Big hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.