Python 为空数据帧创建异常

Python 为空数据帧创建异常,python,Python,我使用用户输入来获取特定股票的历史数据,我想处理2个可能的错误,1个是由于错误输入而生成的错误,代码生成错误;2个是如果输入错误,但代码被执行,我得到一个空数据帧 while True: try: us = input('Enter the symbol of your stock :') us_sd = input('Enter the start date in yyyy-mm-dd :') year, month, day = map

我使用用户输入来获取特定股票的历史数据,我想处理2个可能的错误,1个是由于错误输入而生成的错误,代码生成错误;2个是如果输入错误,但代码被执行,我得到一个空数据帧

while True:
    try:
        us = input('Enter the symbol of your stock :')
        us_sd = input('Enter the start date in yyyy-mm-dd :')
        year, month, day = map(int, us_sd.split("-"))
        us_sd = datetime.date(year,month,day)
        data = ns.get_history(symbol=us.upper(), start=us_sd, end=date.today())
        print(data)
        break
    except Exception as e:
        print('there was an error with your input :{0}'.format(e))
如果发生任何系统错误,但当用户输入错误的股票符号(例如SBI符号为SBIN)时,上述代码会处理,但如果有人输入SBINSE或假设有人输入ZOO作为股票符号,则数据将返回一个没有任何错误的空数据帧,我想设置一个条件,如果返回的数据帧为空,那么循环应该继续进行。请帮忙


在上述代码中,ns是nsepy模块。我的python版本是3.6.4

感谢David A为我指明了正确的方向

if data.empty:
    print('no results, please alter search and try again...')
    continue
这是我在代码中实现的更改,现在它似乎可以处理输入错误股票符号时出现的所有空数据帧问题

while True:

    try:
        us = input('Enter the name of your stock :')
        us_sd = input('Enter the start date in yyyy-mm-dd :')
        year, month, day = map(int, us_sd.split("-"))
        us_sd = datetime.date(year,month,day)
        data = ns.get_history(symbol=us.upper(), start=us_sd, end=date.today())
        if data.empty == True:
            raise RuntimeError('Symbol doesn\'t exist')
        break
    except Exception as e:
        print('There was an error in your input, please try again :{0}'.format(e))

这应该行得通,不过我还没有测试过。你可以自己破例,但没有必要

“错误”是指标题中的例外情况吗?如果是这样,请查看您的大写字母
try
,这将不起作用。抱歉,在此处键入大写字母try是一个错误。这不是这里的问题。谢谢你,这很有帮助。是的,这很有效,这也是乔纳斯在上面发布的答案。非常感谢。
while True:
    try:
        us = input('Enter the symbol of your stock :')
        us_sd = input('Enter the start date in yyyy-mm-dd :')
        year, month, day = map(int, us_sd.split("-"))
        us_sd = datetime.date(year,month,day)
        data = ns.get_history(symbol=us.upper(), start=us_sd, end=date.today())
        if data == None or data.length == 0: // a check that is empty
            raise Exception("Data is empty")

        print(data)
        break
    except Exception as e:
        print('there was an error with your input :{0}'.format(e))