如果行缺失,则数据 == 0。如果不缺失,则使用默认值

if row is missing, data == 0. if not missing use default value

def compute(tick):
    df = pd.read_csv(f'{tick}.csv')
    a = df.loc['a'].sum()
    b = df.loc['b'].sum()
    c = df.loc['c'].sum()
    d = (a + b) / c
    return d

在某些数据帧中没有行 'b',因此它 returns KeyError。然后我尝试了下面的代码,但是它不起作用,谁能帮我提供解决这个问题的方法?

def compute(tick):
    df = pd.read_csv(f'{tick}.csv')
    a = df.loc['a'].sum()
    if df.loc['b'].isnull():
        b == 0
    else:
        b = df.loc['b'].sum()
    c = df.loc['c'].sum()
    d = (a + b) / c
    return d

试试这个

def compute(tick):
    df = pd.read_csv(f'{tick}.csv')
    
    if b in df.columns: #Check if column b exists.
        b = df.loc['b'].sum()
    else:
        b = 0

    a = df.loc['a'].sum()
    c = df.loc['c'].sum()
    d = (a + b) / c
    return d

使用 DataFrame.reindex 添加不存在的值 abc 行,同样在 df 中只有 3 个筛选行:

def compute(tick):
    df = pd.read_csv(f'{tick}.csv').reindex(['a','b','c'], fill_value=0)
    a = df.loc['a'].sum()
    b = df.loc['b'].sum()
    c = df.loc['c'].sum()
    d = (a + b) / c
    return d

如果可以使用相同的功能 3 次,请使用 sum per axis=1:

def compute(tick):
    df = pd.read_csv(f'{tick}.csv').reindex(['a','b','c'], fill_value=0)
    abc = df.sum(axis=1)

    a = abc.loc['a']
    b = abc.loc['b']
    c = abc.loc['c']
    d = (a + b) / c
    return d

怎么样:-

def compute(tick):
    df = pd.read_csv(f'{tick}.csv')
    a = df.loc['a'].sum()
    c = df.loc['c'].sum()
    try:
       return(a + df.loc['b'].sum()) / c
    except KeyError:
       pass
    return a / c