aviss
aviss

Reputation: 2439

ValueError: invalid literal for float(): when adding annotation in pandas

I get this error when I try to add an annotation to my plot - ValueError: invalid literal for float(): 10_May.

my dataframe:

enter image description here

my code (I use to_datetime and strftime before ploting as I needed to sort dates which were stored as strings):

# 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] returns u'10_May' while grouped['L'][9] returns 10.0. I know that pandas expect index to be float but I thought I can access it by df.index[]. Will appreciate your suggestions.

Upvotes: 1

Views: 378

Answers (1)

jezrael
jezrael

Reputation: 862851

For me works first plot and then get index position by 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='-|>'))

Sample:

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

EDIT:

More general solution with 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='-|>'))

Upvotes: 2

Related Questions