Home > Enterprise >  Add new column to DataFrame with same default value
Add new column to DataFrame with same default value

Time:11-24

I would like to add a name column based on the 'lNames' list. But my code is overwriting the whole column in the last iteration as follows:

import pandas as pd

def consulta_bc(codigo_bcb):
    url = 'http://api.bcb.gov.br/dados/serie/bcdata.sgs.{}/dados?formato=json'.format(codigo_bcb)
    df = pd.read_json(url)
    df['data'] = pd.to_datetime(df['data'], dayfirst=True)
    df.set_index('data', inplace=True)
    return df

lCodigos = [12, 11, 1, 21619, 21623, 12466]
lNames =   ['CDI', 'SELIC', 'USD', 'EUR', 'GPB', 'IMAB']

iter_len = len(lCodigos)
saida = pd.DataFrame()

for i in range(iter_len):
    saida = saida.append(consulta_bc(lCodigos[i]))
    saida['nome']= lNames[i]
saida.to_csv('Indice', sep=';', index=True)
saida

Any help will be fully appreciated

CodePudding user response:

Change the for loop in this way:

for i in range(iter_len):
    df = consulta_bc(lCodigos[i])
    df['nome'] = lNames[i]
    saida = saida.append(df)
  • Related