Roman
Roman

Reputation: 3241

appending date in pandas dataframe

I have dataframe as follows:

           Dates
0     2001-01-01
1     2001-01-02
2     2001-01-03
3     2001-01-04

I want to append 2 consecutive dates and get the following dataframe.

           Dates
0     2001-01-01
1     2001-01-02
2     2001-01-03
3     2001-01-04
4     2001-01-05
5     2001-01-06


new = pd.date_range(dates.Dates.iloc[-1], periods=2)
print (new)

Upvotes: 2

Views: 3609

Answers (1)

jezrael
jezrael

Reputation: 862431

Use append, but necessary remove first new value by indexing [1:]:

new = pd.date_range(df.Dates.iloc[-1], periods=3)
s = pd.Series(new[1:])
new = df['Dates'].append(s, ignore_index=True)
print (new)
0   2001-01-01
1   2001-01-02
2   2001-01-03
3   2001-01-04
4   2001-01-05
5   2001-01-06
dtype: datetime64[ns]

new = pd.date_range(df.Dates.iloc[-1], periods=3)
df1 = pd.DataFrame(new[1:], columns=['Dates'])
df = df.append(df1, ignore_index=True)
print (df)
       Dates
0 2001-01-01
1 2001-01-02
2 2001-01-03
3 2001-01-04
4 2001-01-05
5 2001-01-06

Or recontruct DataFrame:

new = pd.date_range(df.Dates.iloc[0], periods=len(df) + 2)
df1 = pd.DataFrame(new, columns=['Dates'])
print (df1)
       Dates
0 2001-01-01
1 2001-01-02
2 2001-01-03
3 2001-01-04
4 2001-01-05
5 2001-01-06

Upvotes: 2

Related Questions