pandas 当KeyError出现以下情况时继续运行代码:空值是否出现“['Column']不在索引中”?

qkf9rpyu  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(149)

当某个符号的"marketCap"列中没有数据时,我得到的是KeyError: "['marketCap'] not in index"。当没有数据时,我如何设置“Null”,这样代码就可以继续运行而不会出错?

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)
hmmo2u0o

hmmo2u0o1#

这是个好主意:

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

相关问题