DramboHero
DramboHero

Reputation: 1103

Add default values to dataframe

I have a dataframe that has hours of day as index, and a value for each hour. like so:

    val
09   1
10   2
12   3
13   3
14   5
17   8

I want to fill the df, with values for all the hours of the day, so it will begin in 00 and go all the way to 23 and fill the value of it with 0.

I guess I can loop on the indexes and check if the value exits or the index and if not to add it, but I don't know how to loop DataFrame and I guess there is an easy way to do the task I want.

Upvotes: 1

Views: 1195

Answers (2)

jezrael
jezrael

Reputation: 862671

One line solution - need reindex by Series with 0 added by zfill and fill 0 by parameter fill_value=0:

print (df.reindex(pd.Series(np.arange(24)).astype(str).str.zfill(2), fill_value=0))
    val
00    0
01    0
02    0
03    0
04    0
05    0
06    0
07    0
08    0
09    1
10    2
11    0
12    3
13    3
14    5
15    0
16    0
17    8
18    0
19    0
20    0
21    0
22    0
23    0

Upvotes: 1

EdChum
EdChum

Reputation: 394041

You can reindex your df, this will place NaN where rows don't exist but you can supply a fill_value=0 to replace these:

In [48]:
df.reindex(np.arange(24), fill_value=0)

Out[48]:
    val
0     0
1     0
2     0
3     0
4     0
5     0
6     0
7     0
8     0
9     1
10    2
11    0
12    3
13    3
14    5
15    0
16    0
17    8
18    0
19    0
20    0
21    0
22    0
23    0

If your index is string dtype you need to cast to int first:

df.index = df.index.astype(int)

then do the above and cast back and left fill the required number of zeroes using str.zfill:

In [49]:
df = df.reindex(np.arange(24), fill_value=0)
df.index = df.index.astype(str).str.zfill(2)
df

Out[49]:
    val
00    0
01    0
02    0
03    0
04    0
05    0
06    0
07    0
08    0
09    1
10    2
11    0
12    3
13    3
14    5
15    0
16    0
17    8
18    0
19    0
20    0
21    0
22    0
23    0

Upvotes: 3

Related Questions