Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas extend DataFrame with Zeros

I have following DataFrame which start by an index of 1.10 and increment by 0.05:

          A       B       C       D       E

1.10      3       2       2       1       0
1.15      1       2       0       1       0
1.20      0       0       0       1      -1
1.25      1       1       3      -5       2
1.30     -3       4       2       6       0
...

I want to extend this DataFrame with zeros that the result looks like this:

          A       B       C       D       E

0         0       0       0       0       0
0.05      0       0       0       0       0
0.10      0       0       0       0       0

...

1.10      3       2       2       1       0
1.15      1       2       0       1       0
1.20      0       0       0       1      -1
1.25      1       1       3      -5       2
1.30     -3       4       2       6       0
...

So I want that the index starts by 0 and increments by 0.05 until the original start index of 1.10 is reached. How to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a reindex with help of numpy.arange:

step = 0.05

out = df.reindex(np.arange(0, df.index.max()+step, step), fill_value=0)

Or if you don’t want to touch the existing DataFrame and only add the missing prior indices (which is more in the spirit of "the index starts by 0 and increments by 0.05 until the original start index of 1.10 is reached"), create the top DataFrame and concat:

step = 0.05

out = pd.concat([pd.DataFrame(0, columns=df.columns,
                              index=np.arange(0, df.index.min(), step)),
                 df])

Output:

      A  B  C  D  E
0.00  0  0  0  0  0
0.05  0  0  0  0  0
0.10  0  0  0  0  0
0.15  0  0  0  0  0
 ...
1.00  0  0  0  0  0
1.05  0  0  0  0  0
1.10  3  2  2  1  0
1.15  0  0  0  0  0
1.20  0  0  0  0  0
1.25  1  1  3 -5  2
1.30 -3  4  2  6  0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading