2017-05-14 64 views
1

当我尝试向我的图中添加注释时出现此错误 - ValueError: invalid literal for float(): 10_MayValueError:无效文字为float():在熊猫中添加注释时

我的数据框:

enter image description here

我的代码(我用to_datetimestrftime ploting之前,我需要整理这些被存储为字符串日期):

# dealing with dates as strings 
grouped.index = pd.to_datetime(grouped.index, format='%d_%b') 
grouped = grouped.sort_index() 
grouped.index = grouped.index.strftime('%d_%b') 
plt.annotate('Peak', 
      (grouped.index[9], grouped['L'][9]), 
      xytext=(15, 15), 
      textcoords='offset points', 
      arrowprops=dict(arrowstyle='-|>')) 
grouped.plot() 

grouped.index[9]回报u'10_May'grouped['L'][9]返回10.0。 我知道熊猫期望指数是浮动的,但我想我可以通过df.index []访问它。将感谢您的建议。

回答

2

对我的作品第一幅图,然后通过Index.get_loc得到索引位置:

ax = df.plot() 
ax.annotate('Peak', 
      (df.index.get_loc(df.index[9]), df['L'][9]), 
      xytext=(15, 15), 
      textcoords='offset points', 
      arrowprops=dict(arrowstyle='-|>')) 

样品:

np.random.seed(10) 
df = pd.DataFrame({'L':[3,5,0,1]}, index=['4_May','3_May','1_May', '2_May']) 
#print (df) 
df.index = pd.to_datetime(df.index, format='%d_%b') 
df = df.sort_index() 
df.index = df.index.strftime('%d_%b') 
df.plot() 
plt.annotate('Peak', 
      (df.index.get_loc(df.index[2]), df['L'][2]), 
      xytext=(15, 15), 
      textcoords='offset points', 
      arrowprops=dict(arrowstyle='-|>')) 

graph

编辑:

更多与get_loc通用的解决方案+ idxmax + max

ax = df.plot() 
ax.annotate('Peak', 
      (df.index.get_loc(df['L'].idxmax()), df['L'].max()), 
      xytext=(15, 15), 
      textcoords='offset points', 
      arrowprops=dict(arrowstyle='-|>')) 
+0

Supeer,周末愉快! – jezrael