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

前端 未结 6 467
日久生厌
日久生厌 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:14

    Here's another option: First add a NaN record on the last day you want, then resample. This way resampling will fill the missing dates for you.

    Starting Frame:

    import pandas as pd
    import numpy as np
    from datetime import date
    
    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('day')
    df2
    
    Out:
                      b
        day 
        2012-01-01  0.22
        2012-01-03  0.30
    

    Filled Frame:

    df2 = df2.set_value(date(2012,1,31),'b',np.float('nan'))
    df2.asfreq('D')
    
    Out:
                    b
        day 
        2012-01-01  0.22
        2012-01-02  NaN
        2012-01-03  0.30
        2012-01-04  NaN
        2012-01-05  NaN
        2012-01-06  NaN
        2012-01-07  NaN
        2012-01-08  NaN
        2012-01-09  NaN
        2012-01-10  NaN
        2012-01-11  NaN
        2012-01-12  NaN
        2012-01-13  NaN
        2012-01-14  NaN
        2012-01-15  NaN
        2012-01-16  NaN
        2012-01-17  NaN
        2012-01-18  NaN
        2012-01-19  NaN
        2012-01-20  NaN
        2012-01-21  NaN
        2012-01-22  NaN
        2012-01-23  NaN
        2012-01-24  NaN
        2012-01-25  NaN
        2012-01-26  NaN
        2012-01-27  NaN
        2012-01-28  NaN
        2012-01-29  NaN
        2012-01-30  NaN
        2012-01-31  NaN
    

提交回复
热议问题