Issue
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
in some dataframes there is no row 'b', so it returns KeyError. Then I tried following code, but it doesnt work, anyone can help me provide a solution to this problem?
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
Solution
Try using this
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
Answered By - Raymond Toh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.