【问题标题】:Python Pandas Dataframe- Setting the Index as datetime with custom monthsPython Pandas Dataframe-将索引设置为具有自定义月份的日期时间
【发布时间】:2018-12-20 15:08:15
【问题描述】:

我有一个看起来像这样的简单数据框。

0       0.00
1       0.00
2       0.07
3       0.09
4       0.09
...
180    13.46
181    13.46
182    15.05
183    15.05
184    15.05
185    15.05

我想将数字索引更改为月份日期,但不按时间顺序。我希望它是一月,二月,三月,四月,十一月,十二月。我怎样才能使索引进入这些自定义月份,以便跳过我不想要的月份?

【问题讨论】:

  • 哪几年?
  • 预期输出是多少?
  • 仅一年。预期的输出将在索引列中包含月份日期,然后在第二列中包含与示例相同的数据。

标签: python pandas datetime dataframe


【解决方案1】:

我认为需要:

np.random.seed(2018)
df = pd.DataFrame({'A':np.random.rand(186)})
#print (df)

#365 days
dates = pd.date_range('01-01-2015', '31-12-2015')
dates = dates[dates.month.isin([1,2,3,4,11,12])].strftime('%b-%d')
print (len(dates))
181

#366 days
dates = pd.date_range('01-01-2000', '31-12-2000')
dates = dates[dates.month.isin([1,2,3,4,11,12])].strftime('%b-%d')
print (len(dates))
182

然后:

#filter DaatFrame for same length
df = df.iloc[:len(dates)]
#assign dates
df.index = dates
print (df.head(10))
               A
Jan-01  0.882349
Jan-02  0.104328
Jan-03  0.907009
Jan-04  0.306399
Jan-05  0.446409
Jan-06  0.589985
Jan-07  0.837111
Jan-08  0.697801
Jan-09  0.802803
Jan-10  0.107215

【讨论】:

  • 我需要结果是月份日期。所以第一列(索引)看起来像:Jan-1、Jan-2、Jan-3.... 一直到 Dec-29、Dec-30、Dec-31。
  • 有问题值是181,df的长度是186
猜你喜欢
  • 2017-01-03
  • 2018-01-24
  • 2015-09-09
  • 2020-01-21
  • 2017-07-27
  • 2020-12-14
  • 2018-01-03
  • 2018-10-30
相关资源
最近更新 更多