1

enter image description here

enter image description here I am trying to add rows where there is a gap between month_count. For example, row 0 has month_count = 0 and row 1 has month_count = 7. How can I add extra 6 rows with month counts being 1,2,3,4,5,6? Also, same situation from row 3 to row 4. I would like to add 2 extra rows with month_count 10 and 11. What is the best way to go about this?

pavlod
  • 13
  • 3
  • can you show us how you tryied to do this? maybe with some code? :) – juuso Mar 27 '20 at 00:07
  • Does this answer your question? [Is it possible to insert a row at an arbitrary position in a dataframe using pandas?](https://stackoverflow.com/questions/15888648/is-it-possible-to-insert-a-row-at-an-arbitrary-position-in-a-dataframe-using-pan) – wwii Mar 27 '20 at 00:17
  • Please don't post images of code, data, or Tracebacks. Copy and paste it as text then format it as code (select it and type `ctrl-k`) ... [Discourage screenshots of code and/or errors](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors) – wwii Mar 27 '20 at 00:18

1 Answers1

3

One way to do this would be to iterate over all of the rows and re-build the DataFrame with the missing rows inserted. Pandas does not support the direct insertion of rows at an index, however you can hack together a solution using pd.concat():

def pandas_insert(df, idx, row_contents):
    top = df.iloc[:idx]
    bot = df.iloc[idx:]

    inserted = pd.concat([top, row_contents, bot], ignore_index=True)

    return inserted

Here row_contents should be a DataFrame with one (or more) rows. We use ignore_index=True to update the index of the new DataFrame to be labeled 0,1, …, n-2, n-1