Catching exception in numpy array element or row
I am performing a row-wise operation on a numpy array. How can I catch possible exceptions so that I can still obtain the other valid rows?
As an example, I'll take the sum of the array's row and divide it through the first or second element in the row. If I catch the created ZeroDivisionError and try to replace it by the number zero, the whole array is replaced. I would like only the excepting element to be replaced.
The actual function is different and the actual error is an OverflowError, this is just for illustrative purposes.
import numpy as np
c = np.array([[1,2,3],[0, 4, 5]])
def catch(func, handle=lambda e : e, *args, **kwargs):
with np.errstate(divide='raise'):
try:
return func(*args, **kwargs)
except Exception as e:
return 0
#divide by second column
def div_arr1(x):
ans = catch(lambda : np.sum(x, axis = 1) / x[:,1] )
return ans
#divide by first column, create ZeroDivisionError
def div_arr0(x):
ans = catch(lambda : np.sum(x, axis = 1) / x[:,0] )
return ans
foo = div_arr1(c)
bar = div_arr0(c) #ZeroDivisionError
print('Divide by second column:' , foo)
print('Divide by first column:' , bar, ' , expected: [6. 0]')
#output
#Divide by second column: [3. 2.25]
#Divide by first column: 0 , expected: [6. 0]
python numpy error-handling
add a comment |
I am performing a row-wise operation on a numpy array. How can I catch possible exceptions so that I can still obtain the other valid rows?
As an example, I'll take the sum of the array's row and divide it through the first or second element in the row. If I catch the created ZeroDivisionError and try to replace it by the number zero, the whole array is replaced. I would like only the excepting element to be replaced.
The actual function is different and the actual error is an OverflowError, this is just for illustrative purposes.
import numpy as np
c = np.array([[1,2,3],[0, 4, 5]])
def catch(func, handle=lambda e : e, *args, **kwargs):
with np.errstate(divide='raise'):
try:
return func(*args, **kwargs)
except Exception as e:
return 0
#divide by second column
def div_arr1(x):
ans = catch(lambda : np.sum(x, axis = 1) / x[:,1] )
return ans
#divide by first column, create ZeroDivisionError
def div_arr0(x):
ans = catch(lambda : np.sum(x, axis = 1) / x[:,0] )
return ans
foo = div_arr1(c)
bar = div_arr0(c) #ZeroDivisionError
print('Divide by second column:' , foo)
print('Divide by first column:' , bar, ' , expected: [6. 0]')
#output
#Divide by second column: [3. 2.25]
#Divide by first column: 0 , expected: [6. 0]
python numpy error-handling
add a comment |
I am performing a row-wise operation on a numpy array. How can I catch possible exceptions so that I can still obtain the other valid rows?
As an example, I'll take the sum of the array's row and divide it through the first or second element in the row. If I catch the created ZeroDivisionError and try to replace it by the number zero, the whole array is replaced. I would like only the excepting element to be replaced.
The actual function is different and the actual error is an OverflowError, this is just for illustrative purposes.
import numpy as np
c = np.array([[1,2,3],[0, 4, 5]])
def catch(func, handle=lambda e : e, *args, **kwargs):
with np.errstate(divide='raise'):
try:
return func(*args, **kwargs)
except Exception as e:
return 0
#divide by second column
def div_arr1(x):
ans = catch(lambda : np.sum(x, axis = 1) / x[:,1] )
return ans
#divide by first column, create ZeroDivisionError
def div_arr0(x):
ans = catch(lambda : np.sum(x, axis = 1) / x[:,0] )
return ans
foo = div_arr1(c)
bar = div_arr0(c) #ZeroDivisionError
print('Divide by second column:' , foo)
print('Divide by first column:' , bar, ' , expected: [6. 0]')
#output
#Divide by second column: [3. 2.25]
#Divide by first column: 0 , expected: [6. 0]
python numpy error-handling
I am performing a row-wise operation on a numpy array. How can I catch possible exceptions so that I can still obtain the other valid rows?
As an example, I'll take the sum of the array's row and divide it through the first or second element in the row. If I catch the created ZeroDivisionError and try to replace it by the number zero, the whole array is replaced. I would like only the excepting element to be replaced.
The actual function is different and the actual error is an OverflowError, this is just for illustrative purposes.
import numpy as np
c = np.array([[1,2,3],[0, 4, 5]])
def catch(func, handle=lambda e : e, *args, **kwargs):
with np.errstate(divide='raise'):
try:
return func(*args, **kwargs)
except Exception as e:
return 0
#divide by second column
def div_arr1(x):
ans = catch(lambda : np.sum(x, axis = 1) / x[:,1] )
return ans
#divide by first column, create ZeroDivisionError
def div_arr0(x):
ans = catch(lambda : np.sum(x, axis = 1) / x[:,0] )
return ans
foo = div_arr1(c)
bar = div_arr0(c) #ZeroDivisionError
print('Divide by second column:' , foo)
print('Divide by first column:' , bar, ' , expected: [6. 0]')
#output
#Divide by second column: [3. 2.25]
#Divide by first column: 0 , expected: [6. 0]
python numpy error-handling
python numpy error-handling
edited Nov 12 at 13:18
asked Nov 12 at 13:06
Cliff
1257
1257
add a comment |
add a comment |
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53262839%2fcatching-exception-in-numpy-array-element-or-row%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53262839%2fcatching-exception-in-numpy-array-element-or-row%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown