简体   繁体   English

如何在 pandas dataframe 中创建新日期并作为索引插入?

[英]How to create new date and insert as index in pandas dataframe?

Im predicting total sales for next month and set the date as index in dataframe.我预测下个月的总销售额并将日期设置为 dataframe 中的索引。 How do I calculate new upcoming month as index and put it in a new row in the same dataframe?如何计算新的下个月作为索引并将其放在同一 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.但是,output 似乎不正确。 Im expecting the result will be like below for the new upcoming index:我预计新的即将推出的索引的结果将如下所示:

2017-07-30 2017-07-30

But, instead, the output is like this:但是,output 是这样的:

(2017-07-30 00:00:00,) (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 :你很接近,删除[]以避免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 [] :[]的 DataFrame 测试指标:

df = pd.DataFrame(index=[last_date])
print (df.index)
MultiIndex([('2017-05-05',)],
           )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM