Convert a/b string to float in pandas The 2019 Stack Overflow Developer Survey Results Are InWhat is the difference between String and string in C#?Convert a string to an enum in C#How do I read / convert an InputStream into a String in Java?Convert bytes to a string?Converting integer to string in Python?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?Does Python have a string 'contains' substring method?How do I convert a String to an int in Java?Change data type of columns in Pandas

Is "plugging out" electronic devices an American expression?

How to create dashed lines/arrows in Illustrator

On the insanity of kings as an argument against Monarchy

How can I create a character who can assume the widest possible range of creature sizes?

The difference between dialogue marks

What is the use of option -o in the useradd command?

I see my dog run

Where does the "burst of radiance" from Holy Weapon originate?

"Riffle" two strings

How to reverse every other sublist of a list?

"To split hairs" vs "To be pedantic"

Carnot-Caratheodory metric

What is the motivation for a law requiring 2 parties to consent for recording a conversation

Manuscript was "unsubmitted" because the manuscript was deposited in Arxiv Preprints

What is the meaning of Triage in Cybersec world?

How come people say “Would of”?

What does "rabbited" mean/imply in this sentence?

How can I fix this gap between bookcases I made?

Can't find the latex code for the ⍎ (down tack jot) symbol

Landlord wants to switch my lease to a "Land contract" to "get back at the city"

How are circuits which use complex ICs normally simulated?

How to manage monthly salary

Access elements in std::string where positon of string is greater than its size

Spanish for "widget"



Convert a/b string to float in pandas



The 2019 Stack Overflow Developer Survey Results Are InWhat is the difference between String and string in C#?Convert a string to an enum in C#How do I read / convert an InputStream into a String in Java?Convert bytes to a string?Converting integer to string in Python?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?Does Python have a string 'contains' substring method?How do I convert a String to an int in Java?Change data type of columns in Pandas



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have dataframe like this:



 score year
5/5 2019
1/2 2018
A 2019


I want to convert score from string to float like 5/5=1, 1/2=0.5, I tried to_numeric but as my values are in a/b form it's returning me none. Please help me with this.










share|improve this question




























    1















    I have dataframe like this:



     score year
    5/5 2019
    1/2 2018
    A 2019


    I want to convert score from string to float like 5/5=1, 1/2=0.5, I tried to_numeric but as my values are in a/b form it's returning me none. Please help me with this.










    share|improve this question
























      1












      1








      1








      I have dataframe like this:



       score year
      5/5 2019
      1/2 2018
      A 2019


      I want to convert score from string to float like 5/5=1, 1/2=0.5, I tried to_numeric but as my values are in a/b form it's returning me none. Please help me with this.










      share|improve this question














      I have dataframe like this:



       score year
      5/5 2019
      1/2 2018
      A 2019


      I want to convert score from string to float like 5/5=1, 1/2=0.5, I tried to_numeric but as my values are in a/b form it's returning me none. Please help me with this.







      python string pandas dataframe






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 8:31









      Barot ShalinBarot Shalin

      305




      305






















          1 Answer
          1






          active

          oldest

          votes


















          4














          You can use pandas.eval with try-except statement:



          def func(x):
          try:
          return pd.eval(x)
          except Exception:
          #for return original
          return x
          #for return None
          #return None

          df['new'] = df['score'].apply(func)
          print (df)
          score year new
          0 5/5 2019 1
          1 1/2 2018 0.5
          2 A 2019 A


          If there is only division is faster solution from @Goyo, thank you:



          import operator

          def func(x):
          try:
          return operator.truediv(*map(int, x.split('/')))
          except Exception:
          #for return original
          return x
          #for return None
          #return None





          share|improve this answer

























          • Can i do anything to return any character as None too like A will be set to None

            – Barot Shalin
            Mar 8 at 8:42






          • 1





            @BarotShalin - sure, only change return x to return None

            – jezrael
            Mar 8 at 8:42






          • 1





            Got it! Thank you very much!

            – Barot Shalin
            Mar 8 at 8:43






          • 3





            operator.truediv(*map(int, x.split('/'))) is one order of magnitude faster in my tests and it won't run arbitrary code.

            – Goyo
            Mar 8 at 9:03











          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%2f55059365%2fconvert-a-b-string-to-float-in-pandas%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4














          You can use pandas.eval with try-except statement:



          def func(x):
          try:
          return pd.eval(x)
          except Exception:
          #for return original
          return x
          #for return None
          #return None

          df['new'] = df['score'].apply(func)
          print (df)
          score year new
          0 5/5 2019 1
          1 1/2 2018 0.5
          2 A 2019 A


          If there is only division is faster solution from @Goyo, thank you:



          import operator

          def func(x):
          try:
          return operator.truediv(*map(int, x.split('/')))
          except Exception:
          #for return original
          return x
          #for return None
          #return None





          share|improve this answer

























          • Can i do anything to return any character as None too like A will be set to None

            – Barot Shalin
            Mar 8 at 8:42






          • 1





            @BarotShalin - sure, only change return x to return None

            – jezrael
            Mar 8 at 8:42






          • 1





            Got it! Thank you very much!

            – Barot Shalin
            Mar 8 at 8:43






          • 3





            operator.truediv(*map(int, x.split('/'))) is one order of magnitude faster in my tests and it won't run arbitrary code.

            – Goyo
            Mar 8 at 9:03















          4














          You can use pandas.eval with try-except statement:



          def func(x):
          try:
          return pd.eval(x)
          except Exception:
          #for return original
          return x
          #for return None
          #return None

          df['new'] = df['score'].apply(func)
          print (df)
          score year new
          0 5/5 2019 1
          1 1/2 2018 0.5
          2 A 2019 A


          If there is only division is faster solution from @Goyo, thank you:



          import operator

          def func(x):
          try:
          return operator.truediv(*map(int, x.split('/')))
          except Exception:
          #for return original
          return x
          #for return None
          #return None





          share|improve this answer

























          • Can i do anything to return any character as None too like A will be set to None

            – Barot Shalin
            Mar 8 at 8:42






          • 1





            @BarotShalin - sure, only change return x to return None

            – jezrael
            Mar 8 at 8:42






          • 1





            Got it! Thank you very much!

            – Barot Shalin
            Mar 8 at 8:43






          • 3





            operator.truediv(*map(int, x.split('/'))) is one order of magnitude faster in my tests and it won't run arbitrary code.

            – Goyo
            Mar 8 at 9:03













          4












          4








          4







          You can use pandas.eval with try-except statement:



          def func(x):
          try:
          return pd.eval(x)
          except Exception:
          #for return original
          return x
          #for return None
          #return None

          df['new'] = df['score'].apply(func)
          print (df)
          score year new
          0 5/5 2019 1
          1 1/2 2018 0.5
          2 A 2019 A


          If there is only division is faster solution from @Goyo, thank you:



          import operator

          def func(x):
          try:
          return operator.truediv(*map(int, x.split('/')))
          except Exception:
          #for return original
          return x
          #for return None
          #return None





          share|improve this answer















          You can use pandas.eval with try-except statement:



          def func(x):
          try:
          return pd.eval(x)
          except Exception:
          #for return original
          return x
          #for return None
          #return None

          df['new'] = df['score'].apply(func)
          print (df)
          score year new
          0 5/5 2019 1
          1 1/2 2018 0.5
          2 A 2019 A


          If there is only division is faster solution from @Goyo, thank you:



          import operator

          def func(x):
          try:
          return operator.truediv(*map(int, x.split('/')))
          except Exception:
          #for return original
          return x
          #for return None
          #return None






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 8 at 9:05

























          answered Mar 8 at 8:36









          jezraeljezrael

          357k26321397




          357k26321397












          • Can i do anything to return any character as None too like A will be set to None

            – Barot Shalin
            Mar 8 at 8:42






          • 1





            @BarotShalin - sure, only change return x to return None

            – jezrael
            Mar 8 at 8:42






          • 1





            Got it! Thank you very much!

            – Barot Shalin
            Mar 8 at 8:43






          • 3





            operator.truediv(*map(int, x.split('/'))) is one order of magnitude faster in my tests and it won't run arbitrary code.

            – Goyo
            Mar 8 at 9:03

















          • Can i do anything to return any character as None too like A will be set to None

            – Barot Shalin
            Mar 8 at 8:42






          • 1





            @BarotShalin - sure, only change return x to return None

            – jezrael
            Mar 8 at 8:42






          • 1





            Got it! Thank you very much!

            – Barot Shalin
            Mar 8 at 8:43






          • 3





            operator.truediv(*map(int, x.split('/'))) is one order of magnitude faster in my tests and it won't run arbitrary code.

            – Goyo
            Mar 8 at 9:03
















          Can i do anything to return any character as None too like A will be set to None

          – Barot Shalin
          Mar 8 at 8:42





          Can i do anything to return any character as None too like A will be set to None

          – Barot Shalin
          Mar 8 at 8:42




          1




          1





          @BarotShalin - sure, only change return x to return None

          – jezrael
          Mar 8 at 8:42





          @BarotShalin - sure, only change return x to return None

          – jezrael
          Mar 8 at 8:42




          1




          1





          Got it! Thank you very much!

          – Barot Shalin
          Mar 8 at 8:43





          Got it! Thank you very much!

          – Barot Shalin
          Mar 8 at 8:43




          3




          3





          operator.truediv(*map(int, x.split('/'))) is one order of magnitude faster in my tests and it won't run arbitrary code.

          – Goyo
          Mar 8 at 9:03





          operator.truediv(*map(int, x.split('/'))) is one order of magnitude faster in my tests and it won't run arbitrary code.

          – Goyo
          Mar 8 at 9:03



















          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%2f55059365%2fconvert-a-b-string-to-float-in-pandas%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

          AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

          Алба-Юлія

          Захаров Федір Захарович