Im predicting total sales for next month and set the date as index in dataframe. How do I calculate new upcoming month as index and put it in a new row in the same dataframe?
I use this code below to get a new date from previous date:
from datetime import timedelta
last_date = df.iloc[[-1]].index
last_date = last_date + timedelta(days=30)
df= df.append(pd.DataFrame(index=[last_date]))
df.tail()
But, the output seemed not correct. Im expecting the result will be like below for the new upcoming index:
2017-07-30
But, instead, the output is like this:
(2017-07-30 00:00:00,)
How can I remove the time and also the unnecessary symbol there?
You are close, remove []
for avoid MultiIndex
:
df = df.append(pd.DataFrame(index=last_date))
Sample :
from datetime import timedelta
rng = pd.date_range('2017-04-03', periods=3)
df = pd.DataFrame({'a': range(3)}, index=rng)
last_date = df.iloc[[-1]].index
last_date = last_date + timedelta(days=30)
df = df.append(pd.DataFrame(index=last_date))
print (df)
a
2017-04-03 0.0
2017-04-04 1.0
2017-04-05 2.0
2017-05-05 NaN
Test index of DataFrame with []
:
df = pd.DataFrame(index=[last_date])
print (df.index)
MultiIndex([('2017-05-05',)],
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.