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

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

    Mark's answer seems to not be working anymore on pandas 1.1.1.

    However, using the same idea, the following works:

    from datetime import datetime
    import pandas as pd
    
    
    # get start and desired end dates
    first_date = df['date'].min()
    today = datetime.today()
    
    # set index
    df.set_index('date', inplace=True)
    
    # and here is were the magic happens
    idx = pd.date_range(first_date, today, freq='D')
    df = df.reindex(idx)
    

    EDIT: just found out that this exact use case is in the docs:

    https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html#pandas.DataFrame.reindex

提交回复
热议问题