Home > OS >  Have a for loop return a dataframe when it produces a string
Have a for loop return a dataframe when it produces a string

Time:10-15

I have a list of tickers I need to retrieve the name for. I am trying to write a loop that returns a dataframe containing the Short_Name and the tic name.

Code below:

a = []
b = ['FFIV', 'FIS', 'FISV', 'FITB', 'FLS', 'FMC']

for i in b: #add 5 rows of data
    stock = yf.Ticker(i)
    a['Short_Name'] = stock.info['shortName']
    a['tic'] = i

Unfortunately when I run this code I get the following error:

TypeError: list indices must be integers or slices, not str

Any help would be fantastic.

CodePudding user response:

Change the first line of code to:

a = pd.DataFrame()

But this is not the way to add a row to a dataframe. Try this:

row = {'Short Name': stock.info['shortName'], 'tic': i}
a = a.append(pd.DataFrame(row))

CodePudding user response:

Use this:

a = []
b = ['FFIV', 'FIS', 'FISV', 'FITB', 'FLS', 'FMC']

for i in b: #add 5 rows of data
    stock = yf.Ticker(i)
    a.append([stock.info['shortName'], i])

df = pd.DataFrame(data=a, columns=['Short_Name', 'tic'])
  • Related