Search code examples
pandasdataframeadditiondate-range

pandas: generate a dataframe, column a: start till end date (months) and two more columns


My question was to generic. Ok, other try. I want a dataframe with monthly dates in the first column a. THen i want to go through the dates and fill the values in row b and c

import pandas as pd
from pandas import *
import datetime as dt

#try to generate a dataframe with dates

#This ist the dataframe, but how can I fill the dates
dfa = pd.DataFrame(columns=['date',  '1G', '10G'])
print(dfa)
#This are the dates, but how to get them into the dataframe
#and how to add values in the empty cells
idx = pd.date_range("2016-01-01", periods=55, freq="M")
ts = pd.Series(range(len(idx)), index=idx)
print(ts)

Solution

  • If need column filled by datetimes:

    dfa = pd.DataFrame({'date':pd.date_range("2016-01-01", periods=55, freq="M"), 
                        '1G':np.nan,
                        '10G':np.nan})
    print (dfa.head())
            date  1G  10G
    0 2016-01-31 NaN  NaN
    1 2016-02-29 NaN  NaN
    2 2016-03-31 NaN  NaN
    3 2016-04-30 NaN  NaN
    4 2016-05-31 NaN  NaN
    

    Or if need DatetimeIndex:

    dfa = pd.DataFrame({'1G':np.nan,
                        '10G':np.nan}, 
                       index=pd.date_range("2016-01-01", periods=55, freq="M"))
    print (dfa.head())
    
                1G  10G
    2016-01-31 NaN  NaN
    2016-02-29 NaN  NaN
    2016-03-31 NaN  NaN
    2016-04-30 NaN  NaN
    2016-05-31 NaN  NaN