{"id":118018,"date":"2020-09-15T12:35:47","date_gmt":"2020-09-15T12:35:47","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=13083"},"modified":"2020-09-15T12:35:47","modified_gmt":"2020-09-15T12:35:47","slug":"how-to-fix-valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous-use-a-any-or-a-all","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/09\/15\/how-to-fix-valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous-use-a-any-or-a-all\/","title":{"rendered":"How to Fix \u201cValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\u201d"},"content":{"rendered":"<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/image-41.png\" alt=\"ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\" class=\"wp-image-13089\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/image-41.png 936w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/image-41-300x35.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/image-41-768x89.png 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/image-41-928x108.png 928w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/09\/image-41-150x17.png 150w\" sizes=\"(max-width: 936px) 100vw, 936px\" \/><\/figure>\n<\/div>\n<p>If you run the following code, you&#8217;ll experience a special <code>ValueError<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import numpy as np\na = np.array([1, 2, 3])\nb = bool(a)\nprint(b)<\/pre>\n<p>The output will be this error message:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()<\/pre>\n<p><strong>Try It Yourself<\/strong> in our interactive browser shell:<\/p>\n<p> <iframe loading=\"lazy\" height=\"600px\" width=\"100%\" src=\"https:\/\/repl.it\/@finxter\/ImpoliteStunningArrays?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"><\/iframe> <\/p>\n<p><strong>Solution<\/strong>: Using the <a href=\"https:\/\/blog.finxter.com\/numpy-tutorial\/\" title=\"NumPy Tutorial \u2013 Everything You Need to Know to Get Started\" target=\"_blank\" rel=\"noreferrer noopener\">Numpy <\/a>functions called <code>logical_and()<\/code> and <code>logical_or()<\/code> instead of Python&#8217;s <a href=\"https:\/\/blog.finxter.com\/how-to-apply-a-logical-operator-to-all-elements-in-a-python-list\/\" title=\"{AND, OR, NOT} How to Apply Logical Operators to All List Elements in Python?\" target=\"_blank\" rel=\"noreferrer noopener\">logical operators<\/a> (&#8220;and&#8221; and &#8220;or&#8221;) is the solution.<\/p>\n<h2>Why does the ValueError occur at all?<\/h2>\n<p>Many programmers who start learning Numpy think they can use Python&#8217;s logical operators while writing code, but the creators of this module have decided that there is not one commonly understood way to rate an array in a boolean context. <\/p>\n<p>It might mean <code>True<\/code> if <em><strong>any <\/strong><\/em>element is <code>True<\/code>, or <code>True<\/code> if <em><strong>all <\/strong><\/em>elements are <code>True<\/code>, or <code>True<\/code> if the array is of non-zero length. And we only mentioned three possibilities&#8212;there are more! <\/p>\n<p>Because different users may have various needs and goals, developers refused to speculate and decided to raise the <code>ValueError<\/code> each time someone tries to evaluate an array in a Boolean context, so what did they give in exchange?<\/p>\n<h2>Logical_and() function &#8211; the equivalent for \u201cand\u201d<\/h2>\n<p>The <code>logical_and()<\/code> function is equivalent to the Python built-in &#8220;and&#8221; logical operator. When we use this function, the program will return an array with <code>True<\/code> and <code>False<\/code> values.\u00a0<\/p>\n<p>This function has two crucial parameters, i.e. our input arrays, which we put after the comma (in this example <code>arr1 &lt; 3<\/code> and <code>arr_2 > 3<\/code>). Let&#8217;s take a look at the example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import numpy as np arr_1 = np.arange(5)\narr_2 = np.arange(6, 10)\narr_3 = np.array(['First', 'Second', 'Third', 'Fourth', 'Fifth']) mask = np.logical_and(arr_1 &lt; 3, arr_2 > 3)\nprint(arr_3[mask])<\/pre>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">['First' 'Second' 'Third']<\/pre>\n<p>The code printed the first, second and third element of the array <code>arr_3<\/code>, because it checked our conditions and it came out that the first three numbers of our arrays meet the conditions at the same time.\u00a0<\/p>\n<h2>Logical_or() function &#8211; the equivalent for \u201cor\u201d<\/h2>\n<p>The functionality is the same as the previous one. It also has two most important parameters&#8212;input arrays. The only difference is in the behavior of the code, after all we want to achieve something different:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import numpy as np arr_1 = np.arange(5)\narr_2 = np.arange(5, 10)\narr_3 = np.array(['First', 'Second', 'Third', 'Fourth', 'Fifth']) mask = np.logical_or(arr_1 >= 3, arr_2 &lt; 3)\nprint(arr_3[mask])<\/pre>\n<p>As at least one of the elements in positions 4 and 5 of our arrays meets our condition, the result is as follows:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">['Fourth' 'Fifth']<\/pre>\n<h2>Logical And with &#8220;&amp;&#8221; and Logical Or with &#8220;|&#8221;<\/h2>\n<p>Instead of writing <code>logical_and()<\/code> or <code>logical_or()<\/code> we can use <code>&amp;<\/code> and <code>|<\/code> symbols. Take a look at this code:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import numpy\narr_1 = np.arange(5)\narr_2 = np.arange(5, 10)\narr_3 = np.array(['First', 'Second', 'Third', 'Fourth', 'Fifth']) # Same functionality as logical_and\nmask = np.array((arr_1 &lt; 3) &amp; (arr_2 > 3))\nprint(arr_3[mask]) # Same functionality as logical_or\nmask = np.array((arr_1 >= 3) | (arr_2 &lt; 3))\nprint(arr_3[mask])<\/pre>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">['Fourth' 'Fifth']\n['First' 'Second' 'Third']<\/pre>\n<h2>any() and all()<\/h2>\n<p>As these two functions appear in the topic, here is a quick explanation of what they do at all!<\/p>\n<p>The function <code>any()<\/code> checks if any of the elements are non-zero and all() checks if all elements are non-zero.These functions takes several parameters, but two are the most important:<\/p>\n<ul>\n<li><code>a<\/code> -> Input array or object that can be converted to an array.<\/li>\n<li><code>axis<\/code> -> Axis or axes along which a logical OR reduction is performed. The default (axis=None) is to perform a logical OR over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis.<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">arr_1 = np.array([[1, 2, 3, 0],[0, 1, 2, 3]]) print('Outputs of function any')\nprint(np.any(arr_1))\nprint(np.any(arr_1, axis=0))\nprint(np.any(arr_1, axis=1)) print('\\nOutputs of function all')\nprint(np.all(arr_1))\nprint(np.all(arr_1, axis=0))\nprint(np.all(arr_1, axis=1))<\/pre>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Outputs of function any:\nTrue\n[ True True True True]\n[ True True] Outputs of function all:\nFalse\n[False True True False]\n[False False]\n<\/pre>\n<p>As you can see, our script checked at the beginning if any values along the axis are not zero.<\/p>\n<p><strong>Note<\/strong>: <code>axis=0<\/code> is a vertical axis and <code>axis=1<\/code> is a horizontal axis.<\/p>\n<h2>Summary<\/h2>\n<p>We learned why there is a ValueError error when we want to use the logical operators built into Python (&#8220;and&#8221; and &#8220;or&#8221;) in logical operations while using arrays. Next, there were 2 equivalents of these logical operators (&#8220;logical_and&#8221; and &#8220;logical_or&#8221;) and an even faster way to achieve the same. Finally, the function any() and all() in the Numpy module was explained.<\/p>\n<h2>References<\/h2>\n<ul>\n<li><a href=\"https:\/\/stackoverflow.com\/questions\/10062954\/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/stackoverflow.com\/questions\/10062954\/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous<\/a><\/li>\n<li><a href=\"https:\/\/numpy.org\/doc\/1.19\/reference\/generated\/numpy.any\">https:\/\/numpy.org\/doc\/1.19\/reference\/generated\/numpy.any<\/a><\/li>\n<li><a href=\"https:\/\/numpy.org\/doc\/1.19\/reference\/generated\/numpy.all.html\">https:\/\/numpy.org\/doc\/1.19\/reference\/generated\/numpy.all.html<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>If you run the following code, you&#8217;ll experience a special ValueError: import numpy as np a = np.array([1, 2, 3]) b = bool(a) print(b) The output will be this error message: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Try It Yourself in our interactive [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-118018","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/118018","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=118018"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/118018\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=118018"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=118018"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=118018"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}