将“非正式”monthday索引转换为datetime索引

2024-04-23 11:58:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列的索引是月日格式的。它不是正式的日期时间索引。此外,该系列包含一年中每一天的一个数据:

       Data_Value
01-01         156
01-02         139
01-03         133
01-04         106
01-05         128
01-06         189

我的目标是用y轴上的“Data_值”和x轴上的12个月绘制一个直线图。但我想画出365个数据,而不是把它们汇总成12个月。像这样:

enter image description here

总之,我的第一个动作是绘制365个数据,忽略了将月份名称放在x轴上的事实:

^{pr2}$

但在上一个命令中,我得到了错误“ValueError:无法将字符串转换为float:'12-31'”。在

有人能把“非正式的”月日指数转换成省略年份的日期时间指数吗?或者有其他的解决方案来达到我设计这个系列的最终目标?谢谢。在


Tags: 数据名称目标datavalue格式时间绘制
2条回答

您可以使用:

np.random.seed(100)
rng = pd.date_range('2017-01-01', periods=365).strftime('%m-%d')
df = pd.DataFrame({ 'Data_value': np.random.randint(1000, size=365)}, index=rng)  
#print (df)
^{pr2}$
print (df)
      01   02   03   04   05   06   07   08   09   10 ...    22   23   24  \
Jan  520  792  835  871  855   79  944  906  350  948 ...   316  570  912   
Feb  900  415  897  141  757  723  612    4  603  955 ...     2  889  617   
Mar  181  283  824  238  369  926  944  303  679  877 ...   618   30   17   
Apr  693  846    0   13  185  460  362  131  582  643 ...   811   36  773   
May  852   95  626  749  631   76  801  314  102  938 ...   419  407  765   
Jun  677  870  122  628  186  295  619  734  819  286 ...    16  524  854   
Jul  138  776  473  712  414  908  658  349  887  604 ...   389  435  346   
Aug  385   14  883  289  148  168  536  477  442  796 ...   730  250  477   
Sep   82  998  401  906  653  593  885  793  194  655 ...   944  754  506   
Oct  144  819  182  183   83  502  356  554  957  760 ...    70  309  994   
Nov  674  131  870  139  305  797  804  861  451  922 ...   723  119   71   
Dec  781  304  466  544  294  296  497  693   93  398 ...   915  716  322   

      25   26   27   28   29   30   31  
Jan  507  649   93   86  386  667  876  
Feb  478  403  994   63    0    0    0  
Mar   53   68  946  488  347  475  979  
Apr  839   38  214   94  738  170    0  
May  521  944  496  789  409  438  262  
Jun  466  621   67  220  223  788    0  
Jul   34  451  862  974  694   77  212  
Aug  736   74  437  798   67  668  933  
Sep  693  657  705  298  861  172    0  
Oct  736  943  944  905  689  821  879  
Nov  829   93  498  804  123  554    0  
Dec  141   87   65  324  182  640  343  

[12 rows x 31 columns]

最后一个^{}

df.plot()

这就是我所做的,正如jezrael所建议的:

向索引中添加一个随机年份以将其转换为日期时间索引:

s.index = '2014-' + s.index.astype(str)
s.index = pd.to_datetime(s.index)
days_s = s.index
days_s = np.array(days_s)

然后设置并绘制绘图:

^{pr2}$

并使用将x轴从%y-%m-%d更改为%m格式mdates.DateFormatter公司名称:

import matplotlib.dates as mdates
monthsFmt = mdates.DateFormatter('%m')
plt.gca().xaxis.set_major_formatter(monthsFmt)

最后,渲染图:

plt.show()

我不知道这个解决方案是否有点草率,但它是有效的。在

相关问题 更多 >