0

I get KeyError: "['marketCap'] not in index" when there is no data in the "marketCap" column for a particular symbol. How do I put "Null" when there's no data so the code can continue running and not error out?

import pandas as pd
from yahooquery import Ticker

symbols = ['MSFT','GOOG','AAPL'] #I have to put 75,000+ symbols here.
header = ["regularMarketPrice", "marketCap"]

for tick in symbols:
    faang = Ticker(tick)
    faang.price
    df = pd.DataFrame(faang.price).T
    df.to_csv('output.csv', mode='a', index=True, header=False, columns=header)

1 Answer 1

0

Got this working:

import pandas as pd
from yahooquery import Ticker

symbols = ['MSFT','GOOG','AAPL'] #I have to put 75,000+ symbols here.
header = ["regularMarketPrice", "marketCap"]

for tick in symbols:
    faang = Ticker(tick)
    faang.price
    df = pd.DataFrame(faang.price,{"regularMarketPrice":[1],"marketCap":[2]}).T  
#adding the {...} fixed a 'scalar value' error as well.
    try:
        df.to_csv('mktcaptest.csv', mode='a', index=True, header=False, columns=header)
    except KeyError:
        continue
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.