pandas - Extend Index of a DataFrame setting all columns for new rows to NaN?

前端 未结 6 465
日久生厌
日久生厌 2021-02-05 03:58

I have time-indexed data:

df2 = pd.DataFrame({ \'day\': pd.Series([date(2012, 1, 1), date(2012, 1, 3)]), \'b\' : pd.Series([0.22, 0.3]) })
df2 = df2.set_index(\'         


        
6条回答
  •  攒了一身酷
    2021-02-05 04:20

    Use this (current as of pandas 1.1.3):

    ix = pd.date_range(start=date(2012, 1, 1), end=date(2012, 1, 31), freq='D')
    df2.reindex(ix)
    

    Which gives:

                   b
    2012-01-01  0.22
    2012-01-02   NaN
    2012-01-03  0.30
    2012-01-04   NaN
    2012-01-05   NaN
    [...]
    2012-01-29   NaN
    2012-01-30   NaN
    2012-01-31   NaN
    

    For older versions of pandas replace pd.date_range with pd.DatetimeIndex.

提交回复
热议问题