python/pandas: convert month int to month name











up vote
9
down vote

favorite
2












Most of the info I found was not in python>pandas>dataframe hence the question.



I want to transform an integer between 1 and 12 into an abbrieviated month name.



I have a df which looks like:



   client Month
1 sss 02
2 yyy 12
3 www 06


I want the df to look like this:



   client Month
1 sss Feb
2 yyy Dec
3 www Jun









share|improve this question


























    up vote
    9
    down vote

    favorite
    2












    Most of the info I found was not in python>pandas>dataframe hence the question.



    I want to transform an integer between 1 and 12 into an abbrieviated month name.



    I have a df which looks like:



       client Month
    1 sss 02
    2 yyy 12
    3 www 06


    I want the df to look like this:



       client Month
    1 sss Feb
    2 yyy Dec
    3 www Jun









    share|improve this question
























      up vote
      9
      down vote

      favorite
      2









      up vote
      9
      down vote

      favorite
      2






      2





      Most of the info I found was not in python>pandas>dataframe hence the question.



      I want to transform an integer between 1 and 12 into an abbrieviated month name.



      I have a df which looks like:



         client Month
      1 sss 02
      2 yyy 12
      3 www 06


      I want the df to look like this:



         client Month
      1 sss Feb
      2 yyy Dec
      3 www Jun









      share|improve this question













      Most of the info I found was not in python>pandas>dataframe hence the question.



      I want to transform an integer between 1 and 12 into an abbrieviated month name.



      I have a df which looks like:



         client Month
      1 sss 02
      2 yyy 12
      3 www 06


      I want the df to look like this:



         client Month
      1 sss Feb
      2 yyy Dec
      3 www Jun






      python date pandas dataframe monthcalendar






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jun 4 '16 at 0:58









      Boosted_d16

      2,714154894




      2,714154894
























          6 Answers
          6






          active

          oldest

          votes

















          up vote
          12
          down vote



          accepted










          You can do this efficiently with combining calendar.month_abbr and df[col].apply()



          import calendar
          df['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])





          share|improve this answer




























            up vote
            4
            down vote













            One way of doing that is with the apply method in the dataframe but, to do that, you need a map to convert the months. You could either do that with a function / dictionary or with Python's own datetime.



            With the datetime it would be something like:



            def mapper(month):
            date = datetime.datetime(2000, month, 1) # You need a dateobject with the proper month
            return date.strftime('%b') # %b returns the months abbreviation, other options [here][1]

            df['Month'].apply(mapper)





            In a simillar way, you could build your own map for custom names. It would look like this:



            months_map = {01: 'Jan', 02: 'Feb'}
            def mapper(month):
            return months_map[month]





            Obviously, you don't need to define this functions explicitly and could use a lambda directly in the apply method.






            share|improve this answer




























              up vote
              3
              down vote













              Use strptime and lambda function for this:



              from time import strptime
              df['Month'] = df['Month'].apply(lambda x: strptime(x,'%b').tm_mon)





              share|improve this answer






























                up vote
                2
                down vote













                You can do this easily with a column apply.



                import pandas as pd

                df = pd.DataFrame({'client':['sss', 'yyy', 'www'], 'Month': ['02', '12', '06']})

                look_up = {'01': 'Jan', '02': 'Feb', '03': 'Mar', '04': 'Apr', '05': 'May',
                '06': 'Jun', '07': 'Jul', '08': 'Aug', '09': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec'}

                df['Month'] = df['Month'].apply(lambda x: look_up[x])
                df

                Month client
                0 Feb sss
                1 Dec yyy
                2 Jun www





                share|improve this answer






























                  up vote
                  0
                  down vote













                  Having tested all of these on a large dataset, I have found the following to be fastest:



                  import calendar
                  def month_mapping():
                  # I'm lazy so I have a stash of functions already written so
                  # I don't have to write them out every time. This returns the
                  # {1:'Jan'....12:'Dec'} dict in the laziest way...
                  abbrevs = {}
                  for month in range (1, 13):
                  abbrevs[month] = calendar.month_abbr[month]
                  return abbrevs

                  abbrevs = month_mapping()

                  df['Month Abbrev'} = df['Date Col'].dt.month.map(mapping)





                  share|improve this answer




























                    up vote
                    0
                    down vote













                    Since the abbreviated month names is the first three letters of their full names, we could first convert the Month column to datetime and then use dt.month_name() to get the full month name and finally use str.slice() method to get the first three letters, all using pandas and only in one line of code:



                    df['Month'] = pd.to_datetime(df['Month'], format='%m').dt.month_name().str.slice(stop=3)

                    df

                    Month client
                    0 Feb sss
                    1 Dec yyy
                    2 Jun www





                    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',
                      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%2f37625334%2fpython-pandas-convert-month-int-to-month-name%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest
































                      6 Answers
                      6






                      active

                      oldest

                      votes








                      6 Answers
                      6






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes








                      up vote
                      12
                      down vote



                      accepted










                      You can do this efficiently with combining calendar.month_abbr and df[col].apply()



                      import calendar
                      df['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])





                      share|improve this answer

























                        up vote
                        12
                        down vote



                        accepted










                        You can do this efficiently with combining calendar.month_abbr and df[col].apply()



                        import calendar
                        df['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])





                        share|improve this answer























                          up vote
                          12
                          down vote



                          accepted







                          up vote
                          12
                          down vote



                          accepted






                          You can do this efficiently with combining calendar.month_abbr and df[col].apply()



                          import calendar
                          df['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])





                          share|improve this answer












                          You can do this efficiently with combining calendar.month_abbr and df[col].apply()



                          import calendar
                          df['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jun 4 '16 at 1:23









                          EoinS

                          3,4661823




                          3,4661823
























                              up vote
                              4
                              down vote













                              One way of doing that is with the apply method in the dataframe but, to do that, you need a map to convert the months. You could either do that with a function / dictionary or with Python's own datetime.



                              With the datetime it would be something like:



                              def mapper(month):
                              date = datetime.datetime(2000, month, 1) # You need a dateobject with the proper month
                              return date.strftime('%b') # %b returns the months abbreviation, other options [here][1]

                              df['Month'].apply(mapper)





                              In a simillar way, you could build your own map for custom names. It would look like this:



                              months_map = {01: 'Jan', 02: 'Feb'}
                              def mapper(month):
                              return months_map[month]





                              Obviously, you don't need to define this functions explicitly and could use a lambda directly in the apply method.






                              share|improve this answer

























                                up vote
                                4
                                down vote













                                One way of doing that is with the apply method in the dataframe but, to do that, you need a map to convert the months. You could either do that with a function / dictionary or with Python's own datetime.



                                With the datetime it would be something like:



                                def mapper(month):
                                date = datetime.datetime(2000, month, 1) # You need a dateobject with the proper month
                                return date.strftime('%b') # %b returns the months abbreviation, other options [here][1]

                                df['Month'].apply(mapper)





                                In a simillar way, you could build your own map for custom names. It would look like this:



                                months_map = {01: 'Jan', 02: 'Feb'}
                                def mapper(month):
                                return months_map[month]





                                Obviously, you don't need to define this functions explicitly and could use a lambda directly in the apply method.






                                share|improve this answer























                                  up vote
                                  4
                                  down vote










                                  up vote
                                  4
                                  down vote









                                  One way of doing that is with the apply method in the dataframe but, to do that, you need a map to convert the months. You could either do that with a function / dictionary or with Python's own datetime.



                                  With the datetime it would be something like:



                                  def mapper(month):
                                  date = datetime.datetime(2000, month, 1) # You need a dateobject with the proper month
                                  return date.strftime('%b') # %b returns the months abbreviation, other options [here][1]

                                  df['Month'].apply(mapper)





                                  In a simillar way, you could build your own map for custom names. It would look like this:



                                  months_map = {01: 'Jan', 02: 'Feb'}
                                  def mapper(month):
                                  return months_map[month]





                                  Obviously, you don't need to define this functions explicitly and could use a lambda directly in the apply method.






                                  share|improve this answer












                                  One way of doing that is with the apply method in the dataframe but, to do that, you need a map to convert the months. You could either do that with a function / dictionary or with Python's own datetime.



                                  With the datetime it would be something like:



                                  def mapper(month):
                                  date = datetime.datetime(2000, month, 1) # You need a dateobject with the proper month
                                  return date.strftime('%b') # %b returns the months abbreviation, other options [here][1]

                                  df['Month'].apply(mapper)





                                  In a simillar way, you could build your own map for custom names. It would look like this:



                                  months_map = {01: 'Jan', 02: 'Feb'}
                                  def mapper(month):
                                  return months_map[month]





                                  Obviously, you don't need to define this functions explicitly and could use a lambda directly in the apply method.







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jun 4 '16 at 1:20









                                  pekapa

                                  506723




                                  506723






















                                      up vote
                                      3
                                      down vote













                                      Use strptime and lambda function for this:



                                      from time import strptime
                                      df['Month'] = df['Month'].apply(lambda x: strptime(x,'%b').tm_mon)





                                      share|improve this answer



























                                        up vote
                                        3
                                        down vote













                                        Use strptime and lambda function for this:



                                        from time import strptime
                                        df['Month'] = df['Month'].apply(lambda x: strptime(x,'%b').tm_mon)





                                        share|improve this answer

























                                          up vote
                                          3
                                          down vote










                                          up vote
                                          3
                                          down vote









                                          Use strptime and lambda function for this:



                                          from time import strptime
                                          df['Month'] = df['Month'].apply(lambda x: strptime(x,'%b').tm_mon)





                                          share|improve this answer














                                          Use strptime and lambda function for this:



                                          from time import strptime
                                          df['Month'] = df['Month'].apply(lambda x: strptime(x,'%b').tm_mon)






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Jun 12 at 2:57









                                          Jarwin

                                          4321425




                                          4321425










                                          answered Mar 22 at 9:27









                                          Vagee

                                          364




                                          364






















                                              up vote
                                              2
                                              down vote













                                              You can do this easily with a column apply.



                                              import pandas as pd

                                              df = pd.DataFrame({'client':['sss', 'yyy', 'www'], 'Month': ['02', '12', '06']})

                                              look_up = {'01': 'Jan', '02': 'Feb', '03': 'Mar', '04': 'Apr', '05': 'May',
                                              '06': 'Jun', '07': 'Jul', '08': 'Aug', '09': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec'}

                                              df['Month'] = df['Month'].apply(lambda x: look_up[x])
                                              df

                                              Month client
                                              0 Feb sss
                                              1 Dec yyy
                                              2 Jun www





                                              share|improve this answer



























                                                up vote
                                                2
                                                down vote













                                                You can do this easily with a column apply.



                                                import pandas as pd

                                                df = pd.DataFrame({'client':['sss', 'yyy', 'www'], 'Month': ['02', '12', '06']})

                                                look_up = {'01': 'Jan', '02': 'Feb', '03': 'Mar', '04': 'Apr', '05': 'May',
                                                '06': 'Jun', '07': 'Jul', '08': 'Aug', '09': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec'}

                                                df['Month'] = df['Month'].apply(lambda x: look_up[x])
                                                df

                                                Month client
                                                0 Feb sss
                                                1 Dec yyy
                                                2 Jun www





                                                share|improve this answer

























                                                  up vote
                                                  2
                                                  down vote










                                                  up vote
                                                  2
                                                  down vote









                                                  You can do this easily with a column apply.



                                                  import pandas as pd

                                                  df = pd.DataFrame({'client':['sss', 'yyy', 'www'], 'Month': ['02', '12', '06']})

                                                  look_up = {'01': 'Jan', '02': 'Feb', '03': 'Mar', '04': 'Apr', '05': 'May',
                                                  '06': 'Jun', '07': 'Jul', '08': 'Aug', '09': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec'}

                                                  df['Month'] = df['Month'].apply(lambda x: look_up[x])
                                                  df

                                                  Month client
                                                  0 Feb sss
                                                  1 Dec yyy
                                                  2 Jun www





                                                  share|improve this answer














                                                  You can do this easily with a column apply.



                                                  import pandas as pd

                                                  df = pd.DataFrame({'client':['sss', 'yyy', 'www'], 'Month': ['02', '12', '06']})

                                                  look_up = {'01': 'Jan', '02': 'Feb', '03': 'Mar', '04': 'Apr', '05': 'May',
                                                  '06': 'Jun', '07': 'Jul', '08': 'Aug', '09': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec'}

                                                  df['Month'] = df['Month'].apply(lambda x: look_up[x])
                                                  df

                                                  Month client
                                                  0 Feb sss
                                                  1 Dec yyy
                                                  2 Jun www






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Sep 27 '17 at 18:08









                                                  Michael

                                                  2,626123863




                                                  2,626123863










                                                  answered Jun 4 '16 at 1:16









                                                  andrew

                                                  2,0191925




                                                  2,0191925






















                                                      up vote
                                                      0
                                                      down vote













                                                      Having tested all of these on a large dataset, I have found the following to be fastest:



                                                      import calendar
                                                      def month_mapping():
                                                      # I'm lazy so I have a stash of functions already written so
                                                      # I don't have to write them out every time. This returns the
                                                      # {1:'Jan'....12:'Dec'} dict in the laziest way...
                                                      abbrevs = {}
                                                      for month in range (1, 13):
                                                      abbrevs[month] = calendar.month_abbr[month]
                                                      return abbrevs

                                                      abbrevs = month_mapping()

                                                      df['Month Abbrev'} = df['Date Col'].dt.month.map(mapping)





                                                      share|improve this answer

























                                                        up vote
                                                        0
                                                        down vote













                                                        Having tested all of these on a large dataset, I have found the following to be fastest:



                                                        import calendar
                                                        def month_mapping():
                                                        # I'm lazy so I have a stash of functions already written so
                                                        # I don't have to write them out every time. This returns the
                                                        # {1:'Jan'....12:'Dec'} dict in the laziest way...
                                                        abbrevs = {}
                                                        for month in range (1, 13):
                                                        abbrevs[month] = calendar.month_abbr[month]
                                                        return abbrevs

                                                        abbrevs = month_mapping()

                                                        df['Month Abbrev'} = df['Date Col'].dt.month.map(mapping)





                                                        share|improve this answer























                                                          up vote
                                                          0
                                                          down vote










                                                          up vote
                                                          0
                                                          down vote









                                                          Having tested all of these on a large dataset, I have found the following to be fastest:



                                                          import calendar
                                                          def month_mapping():
                                                          # I'm lazy so I have a stash of functions already written so
                                                          # I don't have to write them out every time. This returns the
                                                          # {1:'Jan'....12:'Dec'} dict in the laziest way...
                                                          abbrevs = {}
                                                          for month in range (1, 13):
                                                          abbrevs[month] = calendar.month_abbr[month]
                                                          return abbrevs

                                                          abbrevs = month_mapping()

                                                          df['Month Abbrev'} = df['Date Col'].dt.month.map(mapping)





                                                          share|improve this answer












                                                          Having tested all of these on a large dataset, I have found the following to be fastest:



                                                          import calendar
                                                          def month_mapping():
                                                          # I'm lazy so I have a stash of functions already written so
                                                          # I don't have to write them out every time. This returns the
                                                          # {1:'Jan'....12:'Dec'} dict in the laziest way...
                                                          abbrevs = {}
                                                          for month in range (1, 13):
                                                          abbrevs[month] = calendar.month_abbr[month]
                                                          return abbrevs

                                                          abbrevs = month_mapping()

                                                          df['Month Abbrev'} = df['Date Col'].dt.month.map(mapping)






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Oct 23 at 9:35









                                                          Heather

                                                          1




                                                          1






















                                                              up vote
                                                              0
                                                              down vote













                                                              Since the abbreviated month names is the first three letters of their full names, we could first convert the Month column to datetime and then use dt.month_name() to get the full month name and finally use str.slice() method to get the first three letters, all using pandas and only in one line of code:



                                                              df['Month'] = pd.to_datetime(df['Month'], format='%m').dt.month_name().str.slice(stop=3)

                                                              df

                                                              Month client
                                                              0 Feb sss
                                                              1 Dec yyy
                                                              2 Jun www





                                                              share|improve this answer



























                                                                up vote
                                                                0
                                                                down vote













                                                                Since the abbreviated month names is the first three letters of their full names, we could first convert the Month column to datetime and then use dt.month_name() to get the full month name and finally use str.slice() method to get the first three letters, all using pandas and only in one line of code:



                                                                df['Month'] = pd.to_datetime(df['Month'], format='%m').dt.month_name().str.slice(stop=3)

                                                                df

                                                                Month client
                                                                0 Feb sss
                                                                1 Dec yyy
                                                                2 Jun www





                                                                share|improve this answer

























                                                                  up vote
                                                                  0
                                                                  down vote










                                                                  up vote
                                                                  0
                                                                  down vote









                                                                  Since the abbreviated month names is the first three letters of their full names, we could first convert the Month column to datetime and then use dt.month_name() to get the full month name and finally use str.slice() method to get the first three letters, all using pandas and only in one line of code:



                                                                  df['Month'] = pd.to_datetime(df['Month'], format='%m').dt.month_name().str.slice(stop=3)

                                                                  df

                                                                  Month client
                                                                  0 Feb sss
                                                                  1 Dec yyy
                                                                  2 Jun www





                                                                  share|improve this answer














                                                                  Since the abbreviated month names is the first three letters of their full names, we could first convert the Month column to datetime and then use dt.month_name() to get the full month name and finally use str.slice() method to get the first three letters, all using pandas and only in one line of code:



                                                                  df['Month'] = pd.to_datetime(df['Month'], format='%m').dt.month_name().str.slice(stop=3)

                                                                  df

                                                                  Month client
                                                                  0 Feb sss
                                                                  1 Dec yyy
                                                                  2 Jun www






                                                                  share|improve this answer














                                                                  share|improve this answer



                                                                  share|improve this answer








                                                                  edited yesterday

























                                                                  answered yesterday









                                                                  today

                                                                  6,61121333




                                                                  6,61121333






























                                                                       

                                                                      draft saved


                                                                      draft discarded



















































                                                                       


                                                                      draft saved


                                                                      draft discarded














                                                                      StackExchange.ready(
                                                                      function () {
                                                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37625334%2fpython-pandas-convert-month-int-to-month-name%23new-answer', 'question_page');
                                                                      }
                                                                      );

                                                                      Post as a guest




















































































                                                                      Popular posts from this blog

                                                                      Florida Star v. B. J. F.

                                                                      Error while running script in elastic search , gateway timeout

                                                                      Adding quotations to stringified JSON object values