1

I need to sort my data frame by dates recorded as strings so when I plot my values the dates are plotted in order. I grouped it by date grouped = datanew.groupby(['Date']).sum() so sort_values('Date') doesn't work. I tried this

grouped = datanew.sort_values(by='Date',ascending=False).groupby('Date').sum()

I also tried this:

date = sort.reset_index()
sortd = date.sort_values(by='Date', ascending=False)

but in this case, it sorts my df by index not by 'Date' which puzzles me.

Will appreciate your help.

enter image description hereenter image description here

aviss
  • 2,179
  • 7
  • 29
  • 52

1 Answers1

1

I think you can use to_datetime + sort_index + strftime + plot:

df.index = pd.to_datetime(df.index, format='%d_%b')
df = df.sort_index()
df.index = df.index.strftime('%d_%b')
df.plot()

Sample:

np.random.seed(10)
df = pd.DataFrame({'a':[3,5,6,1]}, index=['11_May','12_May','1_May', '2_May'])
print (df)
        a
11_May  3
12_May  5
1_May   6
2_May   1

df.index = pd.to_datetime(df.index, format='%d_%b')
df = df.sort_index()
df.index = df.index.strftime('%d_%b')
print (df)
        a
01_May  6
02_May  1
11_May  3
12_May  5

df.plot()

graph

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Done! :) Thank you. – aviss May 13 '17 at 18:01
  • hi! I hope you can help me a little further with my plot. Now I have a problem adding an annotation. I get this error: `ValueError: invalid literal for float(): 10_May` when trying to access index: `plt.annotate('Peak', (grouped.index[9], grouped['L'][9]), xytext=(15, 15), textcoords='offset points', arrowprops=dict(arrowstyle='-|>'))` I thought that setting index `to_datetime` and then `strftime` solved the problem, but pandas still expects it to be a float... – aviss May 14 '17 at 09:42
  • what return `grouped.index[9]` and what `grouped.index['L'][9]` ? Second seems a bit weird. – jezrael May 14 '17 at 09:54
  • `grouped.index[9]` returns u'10_May' while `grouped['L'][9]` returns 10.0. I'm just trying to locate the point on the graph to add the annotation. – aviss May 14 '17 at 10:05
  • hmmm, do you think something like [this](http://stackoverflow.com/a/41481243/2901002) ? I think the best is create new question - not sure if I know to help, because my knowledge of matplotlib is only basic. Good luck! – jezrael May 14 '17 at 10:14
  • Thank you anyway! Will explore further. – aviss May 14 '17 at 10:41