Python中的异常处理,无需大量except语句

Python中的异常处理,无需大量except语句,python,pandas,Python,Pandas,我正在运行一个附加数据帧的try循环。有时在df中附加一个元素会失败,我不介意,但我希望它被忽略,并继续在try循环中执行其他所有操作。我目前使用的除了:pass,但这意味着在try循环中无法完成其他所有操作 例如,如果它在df['putiv'].loc[i]=put.implicated_volatility处失败,那么该行下方的所有内容都将传递到我不希望的位置,我只希望忽略putiv,并继续前进 代码: import pandas as pd import numpy as np imp

我正在运行一个附加数据帧的try循环。有时在df中附加一个元素会失败,我不介意,但我希望它被忽略,并继续在try循环中执行其他所有操作。我目前使用的
除了:pass
,但这意味着在try循环中无法完成其他所有操作

例如,如果它在
df['putiv'].loc[i]=put.implicated_volatility
处失败,那么该行下方的所有内容都将传递到我不希望的位置,我只希望忽略
putiv
,并继续前进

代码:

import pandas as pd 
import numpy as np 
import wallstreet as ws 
from openpyxl import load_workbook 
import datetime

def day(string_date): 
    return(int(i[0][0]+i[0][1]))

def month(string_date): 
    return(int(i[0][3]+i[0][4]))

def year(string_date): 
    return(int(i[0][6]+i[0][7]+i[0][8]+i[0][9]))

c=ws.Call('AAPL', source='yahoo') 
lst=[(i,j) for i in c.expirations[: 1] for j in c.strikes[25: 30]] 
index=pd.MultiIndex.from_tuples(lst, names=['Expiry', 'Strike']) 


df=pd.DataFrame(index=index, columns=['expDate', 'strike', 'callBid', 'callAsk','callPrice', 'iv', 'delta', 'gamma', 'vega', 'theta', 'rho',\
                                      'putBid', 'putAsk', 'putExp', 'putStrike', 'putiv', 'putDelta', 'putGamma', 'putVega', 'putTheta', 'putRho'])  

for i in df.index: 
   # print('d: ', day(i), 'm: ', month(i), 'y: ', year(i)) 

    try: 
        call=ws.Call('AAPL', source='yahoo', d=day(i), m=month(i), y= year(i)) 
        call.set_strike(i[1])
        put=ws.Put('AAPL', source='yahoo', d=day(i), m=month(i), y= year(i))  
        put.set_strike(i[1]) 

        df['expDate'].loc[i]=call.expiration 
        df['strike'].loc[i]=call.strike 
        df['callBid'].loc[i]=call.bid 
        df['callAsk'].loc[i]=call.ask 
        df['iv'].loc[i]=call.implied_volatility()
        df['callPrice'].loc[i]=call.price 
        df['delta'].loc[i]=call.delta() 
        df['gamma'].loc[i]=call.gamma() 
        df['vega'].loc[i]=call.vega() 
        df['theta'].loc[i]=call.theta()
        df['rho'].loc[i]=call.rho()


        df['putExp'].loc[i]=put.expiration 
        df['putStrike'].loc[i]=put.strike 
        df['putBid'].loc[i]=put.bid 
        df['putAsk'].loc[i]=put.ask 
        df['putPrice'].loc[i]=put.price 
        df['putiv'].loc[i]=put.implied_volatility() 
        df['putDelta'].loc[i]=put.delta() 
        df['putGamma'].loc[i]=put.gamma() 
        df['putVega'].loc[i]=put.vega() 
        df['putTheta'].loc[i]=put.theta()
        df['putRho'].loc[i]=put.rho()

    except KeyboardInterrupt: break
    except: 
        print(i, 'error') 
        pass 

这里的一般技巧是翻译:

df['expDate'].loc[i] = call.expiration 
在包装try/except块的函数调用中:

def set_value(i, col, attr):
    try:
        val = getattr(call, attr)
        # tweak thanks to @cullzie (to ensure it's called if necessary)
        val = val() if callable(val) else val
        df[col].loc[i] = val
    except KeyboardInterrupt:
        raise
    except:
        pass
以便:

df['expDate'].loc[i] = call.expiration 
# becomes
set_value(i, 'expDate', 'expiration')

下面的代码应该做您想做的事情,并将说明被调用的put/call对象的属性或方法。目前默认返回值为“无”,但您可以随意处理

def get_value(obj, attr):
    result = None
    try:
        attribute = getattr(obj, attr) 
        result = attribute() if callable(attribute) else attribute 
    except Exception as e:
        print(str(e))

    return result
示例用法:

    df['iv'].loc[i] = get_value(call, 'implied_volatility')
    df['callPrice'].loc[i] = get_value(call, 'price') 
用于测试的Psuedo调用类I:

class Call(object):
    def __init__(self):
        self.price = 100

    def implied_volatility(self):
        return 0.001

你有没有试过用
try/except
来包装这一行(
df['putiv']=…
),我完全同意。@juanpa.arrivillaga是的@并且,如果你调用隐含波动率的getattr,你会得到如下结果:。我添加了一个涵盖所有情况的答案:@AndyHayden谢谢