Start index at 1 when writing Pandas DataFrame to CSV












27














I need the index to start at 1 rather than 0 when writing a Pandas DataFrame to CSV. Here's an example:



In [1]: import pandas as pd

In [2]: result = pd.DataFrame({'Count': [83, 19, 20]})

In [3]: result.to_csv('result.csv', index_label='Event_id')


Which produces the following output:



In [4]: !cat result.csv
Event_id,Count
0,83
1,19
2,20


But my desired output is this:



In [5]: !cat result2.csv
Event_id,Count
1,83
2,19
3,20


I realize that this could be done by adding a sequence of integers shifted by 1 as a column to my data frame, but I'm new to Pandas and wondering if a cleaner way exists.



Thanks.










share|improve this question



























    27














    I need the index to start at 1 rather than 0 when writing a Pandas DataFrame to CSV. Here's an example:



    In [1]: import pandas as pd

    In [2]: result = pd.DataFrame({'Count': [83, 19, 20]})

    In [3]: result.to_csv('result.csv', index_label='Event_id')


    Which produces the following output:



    In [4]: !cat result.csv
    Event_id,Count
    0,83
    1,19
    2,20


    But my desired output is this:



    In [5]: !cat result2.csv
    Event_id,Count
    1,83
    2,19
    3,20


    I realize that this could be done by adding a sequence of integers shifted by 1 as a column to my data frame, but I'm new to Pandas and wondering if a cleaner way exists.



    Thanks.










    share|improve this question

























      27












      27








      27


      10





      I need the index to start at 1 rather than 0 when writing a Pandas DataFrame to CSV. Here's an example:



      In [1]: import pandas as pd

      In [2]: result = pd.DataFrame({'Count': [83, 19, 20]})

      In [3]: result.to_csv('result.csv', index_label='Event_id')


      Which produces the following output:



      In [4]: !cat result.csv
      Event_id,Count
      0,83
      1,19
      2,20


      But my desired output is this:



      In [5]: !cat result2.csv
      Event_id,Count
      1,83
      2,19
      3,20


      I realize that this could be done by adding a sequence of integers shifted by 1 as a column to my data frame, but I'm new to Pandas and wondering if a cleaner way exists.



      Thanks.










      share|improve this question













      I need the index to start at 1 rather than 0 when writing a Pandas DataFrame to CSV. Here's an example:



      In [1]: import pandas as pd

      In [2]: result = pd.DataFrame({'Count': [83, 19, 20]})

      In [3]: result.to_csv('result.csv', index_label='Event_id')


      Which produces the following output:



      In [4]: !cat result.csv
      Event_id,Count
      0,83
      1,19
      2,20


      But my desired output is this:



      In [5]: !cat result2.csv
      Event_id,Count
      1,83
      2,19
      3,20


      I realize that this could be done by adding a sequence of integers shifted by 1 as a column to my data frame, but I'm new to Pandas and wondering if a cleaner way exists.



      Thanks.







      python csv pandas






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 23 '13 at 21:12









      Clark Fitzgerald

      140127




      140127
























          6 Answers
          6






          active

          oldest

          votes


















          46














          Index is an object, and default index starts from 0:



          >>> result.index
          Int64Index([0, 1, 2], dtype=int64)


          You can shift this index by 1 with



          >>> result.index += 1 
          >>> result.index
          Int64Index([1, 2, 3], dtype=int64)





          share|improve this answer

















          • 2




            somehow it changes index name - so proper order with naming is: df.index+=1;df.index.name='name'
            – yourstruly
            Jul 10 '16 at 16:11





















          7














          Just set the index before writing to csv. df.index = np.arange(1, len(df))



          And then write it normally.






          share|improve this answer





















          • where np is import like so: import numpy as np
            – Dung
            Aug 29 '16 at 21:22












          • it should be df.index = arange( 1, len(df) + 1)
            – Natesh bhat
            Jun 4 '18 at 4:47



















          4














          This worked for me



           df.index = np.arange(1, len(df)+1)





          share|improve this answer





























            3














            source: In Python pandas, start row index from 1 instead of zero without creating additional column



            Working example:



            import pandas as pdas
            dframe = pdas.read_csv(open(input_file))
            dframe.index = dframe.index + 1





            share|improve this answer































              3














              Another way in one line:



              df.shift()[1:]





              share|improve this answer





























                0














                You can use this one:



                import pandas as pd

                result = pd.DataFrame({'Count': [83, 19, 20]})
                result.index += 1
                print(result)


                or this one, by getting the help of numpy library like this:



                import pandas as pd
                import numpy as np

                result = pd.DataFrame({'Count': [83, 19, 20]})
                result.index = np.arange(1, len(result)+1)
                print(result)


                np.arange will create a numpy array and return values within a given interval which is (1, len(result)+1) and finally you will assign that array to result.index.






                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%2f20167930%2fstart-index-at-1-when-writing-pandas-dataframe-to-csv%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  6 Answers
                  6






                  active

                  oldest

                  votes








                  6 Answers
                  6






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  46














                  Index is an object, and default index starts from 0:



                  >>> result.index
                  Int64Index([0, 1, 2], dtype=int64)


                  You can shift this index by 1 with



                  >>> result.index += 1 
                  >>> result.index
                  Int64Index([1, 2, 3], dtype=int64)





                  share|improve this answer

















                  • 2




                    somehow it changes index name - so proper order with naming is: df.index+=1;df.index.name='name'
                    – yourstruly
                    Jul 10 '16 at 16:11


















                  46














                  Index is an object, and default index starts from 0:



                  >>> result.index
                  Int64Index([0, 1, 2], dtype=int64)


                  You can shift this index by 1 with



                  >>> result.index += 1 
                  >>> result.index
                  Int64Index([1, 2, 3], dtype=int64)





                  share|improve this answer

















                  • 2




                    somehow it changes index name - so proper order with naming is: df.index+=1;df.index.name='name'
                    – yourstruly
                    Jul 10 '16 at 16:11
















                  46












                  46








                  46






                  Index is an object, and default index starts from 0:



                  >>> result.index
                  Int64Index([0, 1, 2], dtype=int64)


                  You can shift this index by 1 with



                  >>> result.index += 1 
                  >>> result.index
                  Int64Index([1, 2, 3], dtype=int64)





                  share|improve this answer












                  Index is an object, and default index starts from 0:



                  >>> result.index
                  Int64Index([0, 1, 2], dtype=int64)


                  You can shift this index by 1 with



                  >>> result.index += 1 
                  >>> result.index
                  Int64Index([1, 2, 3], dtype=int64)






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 '13 at 21:57









                  alko

                  28.2k46886




                  28.2k46886








                  • 2




                    somehow it changes index name - so proper order with naming is: df.index+=1;df.index.name='name'
                    – yourstruly
                    Jul 10 '16 at 16:11
















                  • 2




                    somehow it changes index name - so proper order with naming is: df.index+=1;df.index.name='name'
                    – yourstruly
                    Jul 10 '16 at 16:11










                  2




                  2




                  somehow it changes index name - so proper order with naming is: df.index+=1;df.index.name='name'
                  – yourstruly
                  Jul 10 '16 at 16:11






                  somehow it changes index name - so proper order with naming is: df.index+=1;df.index.name='name'
                  – yourstruly
                  Jul 10 '16 at 16:11















                  7














                  Just set the index before writing to csv. df.index = np.arange(1, len(df))



                  And then write it normally.






                  share|improve this answer





















                  • where np is import like so: import numpy as np
                    – Dung
                    Aug 29 '16 at 21:22












                  • it should be df.index = arange( 1, len(df) + 1)
                    – Natesh bhat
                    Jun 4 '18 at 4:47
















                  7














                  Just set the index before writing to csv. df.index = np.arange(1, len(df))



                  And then write it normally.






                  share|improve this answer





















                  • where np is import like so: import numpy as np
                    – Dung
                    Aug 29 '16 at 21:22












                  • it should be df.index = arange( 1, len(df) + 1)
                    – Natesh bhat
                    Jun 4 '18 at 4:47














                  7












                  7








                  7






                  Just set the index before writing to csv. df.index = np.arange(1, len(df))



                  And then write it normally.






                  share|improve this answer












                  Just set the index before writing to csv. df.index = np.arange(1, len(df))



                  And then write it normally.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 '13 at 21:54









                  TomAugspurger

                  15k35055




                  15k35055












                  • where np is import like so: import numpy as np
                    – Dung
                    Aug 29 '16 at 21:22












                  • it should be df.index = arange( 1, len(df) + 1)
                    – Natesh bhat
                    Jun 4 '18 at 4:47


















                  • where np is import like so: import numpy as np
                    – Dung
                    Aug 29 '16 at 21:22












                  • it should be df.index = arange( 1, len(df) + 1)
                    – Natesh bhat
                    Jun 4 '18 at 4:47
















                  where np is import like so: import numpy as np
                  – Dung
                  Aug 29 '16 at 21:22






                  where np is import like so: import numpy as np
                  – Dung
                  Aug 29 '16 at 21:22














                  it should be df.index = arange( 1, len(df) + 1)
                  – Natesh bhat
                  Jun 4 '18 at 4:47




                  it should be df.index = arange( 1, len(df) + 1)
                  – Natesh bhat
                  Jun 4 '18 at 4:47











                  4














                  This worked for me



                   df.index = np.arange(1, len(df)+1)





                  share|improve this answer


























                    4














                    This worked for me



                     df.index = np.arange(1, len(df)+1)





                    share|improve this answer
























                      4












                      4








                      4






                      This worked for me



                       df.index = np.arange(1, len(df)+1)





                      share|improve this answer












                      This worked for me



                       df.index = np.arange(1, len(df)+1)






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Apr 28 '18 at 7:06









                      Liu Yu

                      698




                      698























                          3














                          source: In Python pandas, start row index from 1 instead of zero without creating additional column



                          Working example:



                          import pandas as pdas
                          dframe = pdas.read_csv(open(input_file))
                          dframe.index = dframe.index + 1





                          share|improve this answer




























                            3














                            source: In Python pandas, start row index from 1 instead of zero without creating additional column



                            Working example:



                            import pandas as pdas
                            dframe = pdas.read_csv(open(input_file))
                            dframe.index = dframe.index + 1





                            share|improve this answer


























                              3












                              3








                              3






                              source: In Python pandas, start row index from 1 instead of zero without creating additional column



                              Working example:



                              import pandas as pdas
                              dframe = pdas.read_csv(open(input_file))
                              dframe.index = dframe.index + 1





                              share|improve this answer














                              source: In Python pandas, start row index from 1 instead of zero without creating additional column



                              Working example:



                              import pandas as pdas
                              dframe = pdas.read_csv(open(input_file))
                              dframe.index = dframe.index + 1






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited May 23 '17 at 12:34









                              Community

                              11




                              11










                              answered Aug 29 '16 at 21:11









                              Dung

                              9,31363337




                              9,31363337























                                  3














                                  Another way in one line:



                                  df.shift()[1:]





                                  share|improve this answer


























                                    3














                                    Another way in one line:



                                    df.shift()[1:]





                                    share|improve this answer
























                                      3












                                      3








                                      3






                                      Another way in one line:



                                      df.shift()[1:]





                                      share|improve this answer












                                      Another way in one line:



                                      df.shift()[1:]






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Aug 25 '17 at 14:06









                                      Imran

                                      151210




                                      151210























                                          0














                                          You can use this one:



                                          import pandas as pd

                                          result = pd.DataFrame({'Count': [83, 19, 20]})
                                          result.index += 1
                                          print(result)


                                          or this one, by getting the help of numpy library like this:



                                          import pandas as pd
                                          import numpy as np

                                          result = pd.DataFrame({'Count': [83, 19, 20]})
                                          result.index = np.arange(1, len(result)+1)
                                          print(result)


                                          np.arange will create a numpy array and return values within a given interval which is (1, len(result)+1) and finally you will assign that array to result.index.






                                          share|improve this answer


























                                            0














                                            You can use this one:



                                            import pandas as pd

                                            result = pd.DataFrame({'Count': [83, 19, 20]})
                                            result.index += 1
                                            print(result)


                                            or this one, by getting the help of numpy library like this:



                                            import pandas as pd
                                            import numpy as np

                                            result = pd.DataFrame({'Count': [83, 19, 20]})
                                            result.index = np.arange(1, len(result)+1)
                                            print(result)


                                            np.arange will create a numpy array and return values within a given interval which is (1, len(result)+1) and finally you will assign that array to result.index.






                                            share|improve this answer
























                                              0












                                              0








                                              0






                                              You can use this one:



                                              import pandas as pd

                                              result = pd.DataFrame({'Count': [83, 19, 20]})
                                              result.index += 1
                                              print(result)


                                              or this one, by getting the help of numpy library like this:



                                              import pandas as pd
                                              import numpy as np

                                              result = pd.DataFrame({'Count': [83, 19, 20]})
                                              result.index = np.arange(1, len(result)+1)
                                              print(result)


                                              np.arange will create a numpy array and return values within a given interval which is (1, len(result)+1) and finally you will assign that array to result.index.






                                              share|improve this answer












                                              You can use this one:



                                              import pandas as pd

                                              result = pd.DataFrame({'Count': [83, 19, 20]})
                                              result.index += 1
                                              print(result)


                                              or this one, by getting the help of numpy library like this:



                                              import pandas as pd
                                              import numpy as np

                                              result = pd.DataFrame({'Count': [83, 19, 20]})
                                              result.index = np.arange(1, len(result)+1)
                                              print(result)


                                              np.arange will create a numpy array and return values within a given interval which is (1, len(result)+1) and finally you will assign that array to result.index.







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Nov 23 '18 at 11:00









                                              Utku

                                              691311




                                              691311






























                                                  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.





                                                  Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                  Please pay close attention to the following guidance:


                                                  • 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%2f20167930%2fstart-index-at-1-when-writing-pandas-dataframe-to-csv%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

                                                  Lallio

                                                  Unable to find Lightning Node

                                                  Futebolista