Convert list or numpy array of single element to float in python










14















I have a function which can accept either a list or a numpy array.



In either case, the list/array has a single element (always). I just need to return a float.



So, e.g., I could receive:



list_ = [4]


or the numpy array:



array_ = array([4])


And I should return



 4.0


So, naturally (I would say), I employ float(...) on list_ and get:



TypeError: float() argument must be a string or a number


I do the same to array_ and this time it works by responding with "4.0". From this, I learn that Python's list cannot be converted to float this way.



Based on the success with the numpy array conversion to float this lead me to the approach:



float(np.asarray(list_))


And this works when list_ is both a Python list and when it is a numpy array.



Question



But it seems like this approach has an overhead first converting the list to a numpy array and then to float. Basically: Is there a better way of doing this?










share|improve this question






















  • Can't you use slicing: float(list_[0]) = 4.0

    – Kyrubas
    May 18 '15 at 19:17






  • 1





    either float(list_[0]) or float(''.join(list_))

    – farhawa
    May 18 '15 at 19:21















14















I have a function which can accept either a list or a numpy array.



In either case, the list/array has a single element (always). I just need to return a float.



So, e.g., I could receive:



list_ = [4]


or the numpy array:



array_ = array([4])


And I should return



 4.0


So, naturally (I would say), I employ float(...) on list_ and get:



TypeError: float() argument must be a string or a number


I do the same to array_ and this time it works by responding with "4.0". From this, I learn that Python's list cannot be converted to float this way.



Based on the success with the numpy array conversion to float this lead me to the approach:



float(np.asarray(list_))


And this works when list_ is both a Python list and when it is a numpy array.



Question



But it seems like this approach has an overhead first converting the list to a numpy array and then to float. Basically: Is there a better way of doing this?










share|improve this question






















  • Can't you use slicing: float(list_[0]) = 4.0

    – Kyrubas
    May 18 '15 at 19:17






  • 1





    either float(list_[0]) or float(''.join(list_))

    – farhawa
    May 18 '15 at 19:21













14












14








14


1






I have a function which can accept either a list or a numpy array.



In either case, the list/array has a single element (always). I just need to return a float.



So, e.g., I could receive:



list_ = [4]


or the numpy array:



array_ = array([4])


And I should return



 4.0


So, naturally (I would say), I employ float(...) on list_ and get:



TypeError: float() argument must be a string or a number


I do the same to array_ and this time it works by responding with "4.0". From this, I learn that Python's list cannot be converted to float this way.



Based on the success with the numpy array conversion to float this lead me to the approach:



float(np.asarray(list_))


And this works when list_ is both a Python list and when it is a numpy array.



Question



But it seems like this approach has an overhead first converting the list to a numpy array and then to float. Basically: Is there a better way of doing this?










share|improve this question














I have a function which can accept either a list or a numpy array.



In either case, the list/array has a single element (always). I just need to return a float.



So, e.g., I could receive:



list_ = [4]


or the numpy array:



array_ = array([4])


And I should return



 4.0


So, naturally (I would say), I employ float(...) on list_ and get:



TypeError: float() argument must be a string or a number


I do the same to array_ and this time it works by responding with "4.0". From this, I learn that Python's list cannot be converted to float this way.



Based on the success with the numpy array conversion to float this lead me to the approach:



float(np.asarray(list_))


And this works when list_ is both a Python list and when it is a numpy array.



Question



But it seems like this approach has an overhead first converting the list to a numpy array and then to float. Basically: Is there a better way of doing this?







python arrays list numpy floating-point






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked May 18 '15 at 19:16









denvardenvar

1,51761838




1,51761838












  • Can't you use slicing: float(list_[0]) = 4.0

    – Kyrubas
    May 18 '15 at 19:17






  • 1





    either float(list_[0]) or float(''.join(list_))

    – farhawa
    May 18 '15 at 19:21

















  • Can't you use slicing: float(list_[0]) = 4.0

    – Kyrubas
    May 18 '15 at 19:17






  • 1





    either float(list_[0]) or float(''.join(list_))

    – farhawa
    May 18 '15 at 19:21
















Can't you use slicing: float(list_[0]) = 4.0

– Kyrubas
May 18 '15 at 19:17





Can't you use slicing: float(list_[0]) = 4.0

– Kyrubas
May 18 '15 at 19:17




1




1





either float(list_[0]) or float(''.join(list_))

– farhawa
May 18 '15 at 19:21





either float(list_[0]) or float(''.join(list_))

– farhawa
May 18 '15 at 19:21












4 Answers
4






active

oldest

votes


















17














Just access the first item of the list/array, using the index access and the index 0:



>>> list_ = [4]
>>> list_[0]
4
>>> array_ = np.array([4])
>>> array_[0]
4


This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:



>>> float(list_[0])
4.0





share|improve this answer






























    10














    You may want to use the ndarray.item method, as in a.item(). This is also equivalent to np.asscalar(a). This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,



    >>> a = np.asarray(1).view()
    >>> a.item() # correct
    1

    >>> a[0] # breaks
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    IndexError: too many indices for array


    >>> a = np.asarray([[2]])
    >>> a.item() # correct
    2

    >>> a[0] # bad result
    array([2])


    This also has the benefit of throwing an exception if the array is not a singleton, while the a[0] approach will silently proceed (which may lead to bugs sneaking through undetected).



    >>> a = np.asarray([1, 2])
    >>> a[0] # silently proceeds
    1
    >>> a.item() # detects incorrect size
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    ValueError: can only convert an array of size 1 to a Python scalar





    share|improve this answer
































      4














      Use numpy.asscalar to convert a numpy array / matrix a scalar value:



      >>> a=numpy.array([[[[42]]]])
      >>> numpy.asscalar(a)
      42



      The output data type is the same type returned by the input’s item method.




      It has built in error-checking if there is more than an single element:



      >>> a=numpy.array([1, 2])
      >>> numpy.asscalar(a)


      gives:



      ValueError: can only convert an array of size 1 to a Python scalar



      Note: the object passed to asscalar must respond to item, so passing a list or tuple won't work.






      share|improve this answer






























        2














        I would simply use,



        np.asarray(input, dtype=np.float)[0]


        • If input is an ndarray of the right dtype, there is no overhead, since np.asarray does nothing in this case.

        • if input is a list, np.asarray makes sure the output is of the right type.





        share|improve this answer






















          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
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f30311172%2fconvert-list-or-numpy-array-of-single-element-to-float-in-python%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          17














          Just access the first item of the list/array, using the index access and the index 0:



          >>> list_ = [4]
          >>> list_[0]
          4
          >>> array_ = np.array([4])
          >>> array_[0]
          4


          This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:



          >>> float(list_[0])
          4.0





          share|improve this answer



























            17














            Just access the first item of the list/array, using the index access and the index 0:



            >>> list_ = [4]
            >>> list_[0]
            4
            >>> array_ = np.array([4])
            >>> array_[0]
            4


            This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:



            >>> float(list_[0])
            4.0





            share|improve this answer

























              17












              17








              17







              Just access the first item of the list/array, using the index access and the index 0:



              >>> list_ = [4]
              >>> list_[0]
              4
              >>> array_ = np.array([4])
              >>> array_[0]
              4


              This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:



              >>> float(list_[0])
              4.0





              share|improve this answer













              Just access the first item of the list/array, using the index access and the index 0:



              >>> list_ = [4]
              >>> list_[0]
              4
              >>> array_ = np.array([4])
              >>> array_[0]
              4


              This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:



              >>> float(list_[0])
              4.0






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered May 18 '15 at 19:18









              pokepoke

              210k46329387




              210k46329387























                  10














                  You may want to use the ndarray.item method, as in a.item(). This is also equivalent to np.asscalar(a). This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,



                  >>> a = np.asarray(1).view()
                  >>> a.item() # correct
                  1

                  >>> a[0] # breaks
                  Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                  IndexError: too many indices for array


                  >>> a = np.asarray([[2]])
                  >>> a.item() # correct
                  2

                  >>> a[0] # bad result
                  array([2])


                  This also has the benefit of throwing an exception if the array is not a singleton, while the a[0] approach will silently proceed (which may lead to bugs sneaking through undetected).



                  >>> a = np.asarray([1, 2])
                  >>> a[0] # silently proceeds
                  1
                  >>> a.item() # detects incorrect size
                  Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                  ValueError: can only convert an array of size 1 to a Python scalar





                  share|improve this answer





























                    10














                    You may want to use the ndarray.item method, as in a.item(). This is also equivalent to np.asscalar(a). This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,



                    >>> a = np.asarray(1).view()
                    >>> a.item() # correct
                    1

                    >>> a[0] # breaks
                    Traceback (most recent call last):
                    File "<stdin>", line 1, in <module>
                    IndexError: too many indices for array


                    >>> a = np.asarray([[2]])
                    >>> a.item() # correct
                    2

                    >>> a[0] # bad result
                    array([2])


                    This also has the benefit of throwing an exception if the array is not a singleton, while the a[0] approach will silently proceed (which may lead to bugs sneaking through undetected).



                    >>> a = np.asarray([1, 2])
                    >>> a[0] # silently proceeds
                    1
                    >>> a.item() # detects incorrect size
                    Traceback (most recent call last):
                    File "<stdin>", line 1, in <module>
                    ValueError: can only convert an array of size 1 to a Python scalar





                    share|improve this answer



























                      10












                      10








                      10







                      You may want to use the ndarray.item method, as in a.item(). This is also equivalent to np.asscalar(a). This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,



                      >>> a = np.asarray(1).view()
                      >>> a.item() # correct
                      1

                      >>> a[0] # breaks
                      Traceback (most recent call last):
                      File "<stdin>", line 1, in <module>
                      IndexError: too many indices for array


                      >>> a = np.asarray([[2]])
                      >>> a.item() # correct
                      2

                      >>> a[0] # bad result
                      array([2])


                      This also has the benefit of throwing an exception if the array is not a singleton, while the a[0] approach will silently proceed (which may lead to bugs sneaking through undetected).



                      >>> a = np.asarray([1, 2])
                      >>> a[0] # silently proceeds
                      1
                      >>> a.item() # detects incorrect size
                      Traceback (most recent call last):
                      File "<stdin>", line 1, in <module>
                      ValueError: can only convert an array of size 1 to a Python scalar





                      share|improve this answer















                      You may want to use the ndarray.item method, as in a.item(). This is also equivalent to np.asscalar(a). This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,



                      >>> a = np.asarray(1).view()
                      >>> a.item() # correct
                      1

                      >>> a[0] # breaks
                      Traceback (most recent call last):
                      File "<stdin>", line 1, in <module>
                      IndexError: too many indices for array


                      >>> a = np.asarray([[2]])
                      >>> a.item() # correct
                      2

                      >>> a[0] # bad result
                      array([2])


                      This also has the benefit of throwing an exception if the array is not a singleton, while the a[0] approach will silently proceed (which may lead to bugs sneaking through undetected).



                      >>> a = np.asarray([1, 2])
                      >>> a[0] # silently proceeds
                      1
                      >>> a.item() # detects incorrect size
                      Traceback (most recent call last):
                      File "<stdin>", line 1, in <module>
                      ValueError: can only convert an array of size 1 to a Python scalar






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 13 '18 at 0:47

























                      answered Apr 26 '17 at 17:53









                      Aaron VoelkerAaron Voelker

                      301310




                      301310





















                          4














                          Use numpy.asscalar to convert a numpy array / matrix a scalar value:



                          >>> a=numpy.array([[[[42]]]])
                          >>> numpy.asscalar(a)
                          42



                          The output data type is the same type returned by the input’s item method.




                          It has built in error-checking if there is more than an single element:



                          >>> a=numpy.array([1, 2])
                          >>> numpy.asscalar(a)


                          gives:



                          ValueError: can only convert an array of size 1 to a Python scalar



                          Note: the object passed to asscalar must respond to item, so passing a list or tuple won't work.






                          share|improve this answer



























                            4














                            Use numpy.asscalar to convert a numpy array / matrix a scalar value:



                            >>> a=numpy.array([[[[42]]]])
                            >>> numpy.asscalar(a)
                            42



                            The output data type is the same type returned by the input’s item method.




                            It has built in error-checking if there is more than an single element:



                            >>> a=numpy.array([1, 2])
                            >>> numpy.asscalar(a)


                            gives:



                            ValueError: can only convert an array of size 1 to a Python scalar



                            Note: the object passed to asscalar must respond to item, so passing a list or tuple won't work.






                            share|improve this answer

























                              4












                              4








                              4







                              Use numpy.asscalar to convert a numpy array / matrix a scalar value:



                              >>> a=numpy.array([[[[42]]]])
                              >>> numpy.asscalar(a)
                              42



                              The output data type is the same type returned by the input’s item method.




                              It has built in error-checking if there is more than an single element:



                              >>> a=numpy.array([1, 2])
                              >>> numpy.asscalar(a)


                              gives:



                              ValueError: can only convert an array of size 1 to a Python scalar



                              Note: the object passed to asscalar must respond to item, so passing a list or tuple won't work.






                              share|improve this answer













                              Use numpy.asscalar to convert a numpy array / matrix a scalar value:



                              >>> a=numpy.array([[[[42]]]])
                              >>> numpy.asscalar(a)
                              42



                              The output data type is the same type returned by the input’s item method.




                              It has built in error-checking if there is more than an single element:



                              >>> a=numpy.array([1, 2])
                              >>> numpy.asscalar(a)


                              gives:



                              ValueError: can only convert an array of size 1 to a Python scalar



                              Note: the object passed to asscalar must respond to item, so passing a list or tuple won't work.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Mar 14 '18 at 8:07









                              Tom HaleTom Hale

                              6,8714258




                              6,8714258





















                                  2














                                  I would simply use,



                                  np.asarray(input, dtype=np.float)[0]


                                  • If input is an ndarray of the right dtype, there is no overhead, since np.asarray does nothing in this case.

                                  • if input is a list, np.asarray makes sure the output is of the right type.





                                  share|improve this answer



























                                    2














                                    I would simply use,



                                    np.asarray(input, dtype=np.float)[0]


                                    • If input is an ndarray of the right dtype, there is no overhead, since np.asarray does nothing in this case.

                                    • if input is a list, np.asarray makes sure the output is of the right type.





                                    share|improve this answer

























                                      2












                                      2








                                      2







                                      I would simply use,



                                      np.asarray(input, dtype=np.float)[0]


                                      • If input is an ndarray of the right dtype, there is no overhead, since np.asarray does nothing in this case.

                                      • if input is a list, np.asarray makes sure the output is of the right type.





                                      share|improve this answer













                                      I would simply use,



                                      np.asarray(input, dtype=np.float)[0]


                                      • If input is an ndarray of the right dtype, there is no overhead, since np.asarray does nothing in this case.

                                      • if input is a list, np.asarray makes sure the output is of the right type.






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered May 18 '15 at 19:22









                                      rthrth

                                      5,74422456




                                      5,74422456



























                                          draft saved

                                          draft discarded
















































                                          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.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f30311172%2fconvert-list-or-numpy-array-of-single-element-to-float-in-python%23new-answer', 'question_page');

                                          );

                                          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







                                          Popular posts from this blog

                                          Darth Vader #20

                                          How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

                                          Ondo