0

My current dataframe is as such:

Index     M0      M2      M3
    0    121    2520      -3
    4    121    2521      -3
    5    161    2321      -2
...

Currently, I have no index 1, 2, and so on. I would like to make this available by creating empty records. The end result is like this:

Index     M0      M2      M3
    0    121    2520      -3
    1      0       0       0
    2      0       0       0
    3      0       0       0
    4    121    2521      -3
    5    161    2321      -2
...

I believe this is achievable by usual programming, but I would like to know if I can perform such operation using pandas library.

dee cue
  • 983
  • 1
  • 7
  • 23
  • In addition, what I would do in usual programming is that I will convert the existing dataframe into list, and then iterate through the list to create empty rows. – dee cue Jun 04 '19 at 23:37
  • Do you need to keep the old indices? A simple method would be to simply reindex the data frame. – Paul92 Jun 04 '19 at 23:38
  • Yes, the indices are important. – dee cue Jun 04 '19 at 23:39

2 Answers2

4

Try reindex and fill the new nan rows with 0:

df.reindex(range(df.index.min(), df.index.max()+1)).fillna(0)

Output:

       M0       M2      M3
Index           
0      121.0    2520.0  -3.0
1      0.0      0.0      0.0
2      0.0      0.0      0.0
3      0.0      0.0      0.0
4      121.0    2521.0  -3.0
5      161.0    2321.0  -2.0
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
1

A slight improvement of the previous method is to use the fill_value argument of reindex.

df.reindex(range(df.index.min(), df.index.max()+1), fill_value=0)
GZ0
  • 4,055
  • 1
  • 10
  • 21