Assigning a variable in Python using analogue of '.format()' The 2019 Stack Overflow Developer Survey Results Are InCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonUsing global variables in a functionDoes Python have a string 'contains' substring method?Python string formatting: % vs. .format

Make it rain characters

The following signatures were invalid: EXPKEYSIG 1397BC53640DB551

Do ℕ, mathbbN, BbbN, symbbN effectively differ, and is there a "canonical" specification of the naturals?

Is 'stolen' appropriate word?

Do warforged have souls?

Was credit for the black hole image misappropriated?

Circular reasoning in L'Hopital's rule

What do I do when my TA workload is more than expected?

How do you keep chess fun when your opponent constantly beats you?

Why don't hard Brexiteers insist on a hard border to prevent illegal immigration after Brexit?

How to substitute curly brackets with round brackets in a grid of list

Is it ok to offer lower paid work as a trial period before negotiating for a full-time job?

Grounding Vcc and Vee?

how can a perfect fourth interval be considered either consonant or dissonant?

Can withdrawing asylum be illegal?

Solving overdetermined system by QR decomposition

For what reasons would an animal species NOT cross a *horizontal* land bridge?

60's-70's movie: home appliances revolting against the owners

How many cones with angle theta can I pack into the unit sphere?

Are spiders unable to hurt humans, especially very small spiders?

Quantum Toffoli gate equation

Why are Marketing Cloud timestamps not stored in the same timezone as Sales Cloud?

Categorical vs continuous feature selection/engineering

Accepted by European university, rejected by all American ones I applied to? Possible reasons?



Assigning a variable in Python using analogue of '.format()'



The 2019 Stack Overflow Developer Survey Results Are InCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonUsing global variables in a functionDoes Python have a string 'contains' substring method?Python string formatting: % vs. .format



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








0















I have a dataset with several columns of which I want to convert from categorical to numerical dtype.



I have defined the following function:



def create_num_column(df,column):
df[str(column)]=df[str(column)].astype('category')
df[str(column)+'_cat']=df[str(column)].cat.codes

dictionary.format(str(column)+'_cat')=dict(zip(df[column],df[str(column)+'_cat']))
return dictionary.format(str(column)+'_cat')


I also want this function to create a dictionary so I will be able to understand what label was assigned to what value.



The problem here arises with naming of a dictionary as I have tried to use '.format()' and it has shown syntax error.




dictionary.format(str(column)+'_cat')=dict(zip(df.column,df[str(column)+'_cat']))



>SyntaxError: invalid syntax




I understand that this particular method works with strings but is there any way to 'automate' the naming of variable?



Thanks in advance.










share|improve this question















migrated from datascience.stackexchange.com Mar 30 at 18:27


This question came from our site for Data science professionals, Machine Learning specialists, and those interested in learning more about the field.
























    0















    I have a dataset with several columns of which I want to convert from categorical to numerical dtype.



    I have defined the following function:



    def create_num_column(df,column):
    df[str(column)]=df[str(column)].astype('category')
    df[str(column)+'_cat']=df[str(column)].cat.codes

    dictionary.format(str(column)+'_cat')=dict(zip(df[column],df[str(column)+'_cat']))
    return dictionary.format(str(column)+'_cat')


    I also want this function to create a dictionary so I will be able to understand what label was assigned to what value.



    The problem here arises with naming of a dictionary as I have tried to use '.format()' and it has shown syntax error.




    dictionary.format(str(column)+'_cat')=dict(zip(df.column,df[str(column)+'_cat']))



    >SyntaxError: invalid syntax




    I understand that this particular method works with strings but is there any way to 'automate' the naming of variable?



    Thanks in advance.










    share|improve this question















    migrated from datascience.stackexchange.com Mar 30 at 18:27


    This question came from our site for Data science professionals, Machine Learning specialists, and those interested in learning more about the field.




















      0












      0








      0








      I have a dataset with several columns of which I want to convert from categorical to numerical dtype.



      I have defined the following function:



      def create_num_column(df,column):
      df[str(column)]=df[str(column)].astype('category')
      df[str(column)+'_cat']=df[str(column)].cat.codes

      dictionary.format(str(column)+'_cat')=dict(zip(df[column],df[str(column)+'_cat']))
      return dictionary.format(str(column)+'_cat')


      I also want this function to create a dictionary so I will be able to understand what label was assigned to what value.



      The problem here arises with naming of a dictionary as I have tried to use '.format()' and it has shown syntax error.




      dictionary.format(str(column)+'_cat')=dict(zip(df.column,df[str(column)+'_cat']))



      >SyntaxError: invalid syntax




      I understand that this particular method works with strings but is there any way to 'automate' the naming of variable?



      Thanks in advance.










      share|improve this question
















      I have a dataset with several columns of which I want to convert from categorical to numerical dtype.



      I have defined the following function:



      def create_num_column(df,column):
      df[str(column)]=df[str(column)].astype('category')
      df[str(column)+'_cat']=df[str(column)].cat.codes

      dictionary.format(str(column)+'_cat')=dict(zip(df[column],df[str(column)+'_cat']))
      return dictionary.format(str(column)+'_cat')


      I also want this function to create a dictionary so I will be able to understand what label was assigned to what value.



      The problem here arises with naming of a dictionary as I have tried to use '.format()' and it has shown syntax error.




      dictionary.format(str(column)+'_cat')=dict(zip(df.column,df[str(column)+'_cat']))



      >SyntaxError: invalid syntax




      I understand that this particular method works with strings but is there any way to 'automate' the naming of variable?



      Thanks in advance.







      python






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 30 at 18:34







      user641597

















      asked Mar 30 at 16:57









      user641597user641597

      11




      11




      migrated from datascience.stackexchange.com Mar 30 at 18:27


      This question came from our site for Data science professionals, Machine Learning specialists, and those interested in learning more about the field.









      migrated from datascience.stackexchange.com Mar 30 at 18:27


      This question came from our site for Data science professionals, Machine Learning specialists, and those interested in learning more about the field.
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You cannot "dynamically" name a variable, and there is no need to do so. Simply return the dictionary:



          def create_num_column(df,column):
          df[str(column)]=df[str(column)].astype('category')
          df[str(column)+'_cat']=df[str(column)].cat.codes

          return dict(zip(df.column,df[str(column)+'_cat']))


          (There is a way to create variables or more generally objects with dynamic names in Python, but that's only very rarely useful.)






          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%2f55434472%2fassigning-a-variable-in-python-using-analogue-of-format%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









            0














            You cannot "dynamically" name a variable, and there is no need to do so. Simply return the dictionary:



            def create_num_column(df,column):
            df[str(column)]=df[str(column)].astype('category')
            df[str(column)+'_cat']=df[str(column)].cat.codes

            return dict(zip(df.column,df[str(column)+'_cat']))


            (There is a way to create variables or more generally objects with dynamic names in Python, but that's only very rarely useful.)






            share|improve this answer



























              0














              You cannot "dynamically" name a variable, and there is no need to do so. Simply return the dictionary:



              def create_num_column(df,column):
              df[str(column)]=df[str(column)].astype('category')
              df[str(column)+'_cat']=df[str(column)].cat.codes

              return dict(zip(df.column,df[str(column)+'_cat']))


              (There is a way to create variables or more generally objects with dynamic names in Python, but that's only very rarely useful.)






              share|improve this answer

























                0












                0








                0







                You cannot "dynamically" name a variable, and there is no need to do so. Simply return the dictionary:



                def create_num_column(df,column):
                df[str(column)]=df[str(column)].astype('category')
                df[str(column)+'_cat']=df[str(column)].cat.codes

                return dict(zip(df.column,df[str(column)+'_cat']))


                (There is a way to create variables or more generally objects with dynamic names in Python, but that's only very rarely useful.)






                share|improve this answer













                You cannot "dynamically" name a variable, and there is no need to do so. Simply return the dictionary:



                def create_num_column(df,column):
                df[str(column)]=df[str(column)].astype('category')
                df[str(column)+'_cat']=df[str(column)].cat.codes

                return dict(zip(df.column,df[str(column)+'_cat']))


                (There is a way to create variables or more generally objects with dynamic names in Python, but that's only very rarely useful.)







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 30 at 18:33









                IonicSolutionsIonicSolutions

                962718




                962718





























                    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%2f55434472%2fassigning-a-variable-in-python-using-analogue-of-format%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

                    Adding axes to figuresAdding axes labels to LaTeX figuresLaTeX equivalent of ConTeXt buffersRotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?TikZ scaling graphic and adjust node position and keep font sizeNumerical conditional within tikz keys?adding axes to shapesAlign axes across subfiguresAdding figures with a certain orderLine up nested tikz enviroments or how to get rid of themAdding axes labels to LaTeX figures

                    Luettelo Yhdysvaltain laivaston lentotukialuksista Lähteet | Navigointivalikko

                    Gary (muusikko) Sisällysluettelo Historia | Rockin' High | Lähteet | Aiheesta muualla | NavigointivalikkoInfobox OKTuomas "Gary" Keskinen Ancaran kitaristiksiProjekti Rockin' High