找到图形的峰值和底部并标记它们

  df1

      Date           Topic  Return

      1/1/2010        A,B     -0.308648967

      1/2/2010        C,D     -0.465862046

      1/3/2010        E        0.374052392

      1/4/2010        F        0.520312204

      1/5/2010        G        0.503889198

      1/6/2010        H       -1.730646788

      1/7/2010        L,M,N    1.756295613

      1/8/2010        K        -0.598990239

      ......

      1/30/2010       z         2,124355

 Plot= df1.plot(x='Date', y='Return')

我怎样才能找到这个图的最高点和最低点,并用相应的主题标记这些特殊点?


一只名叫tom的猫
浏览 119回答 2
2回答

慕森王

import numpy as npimport pandas as pdimport matplotlib.pyplot as plt# Take an example datadata = {"Date":["date{i}".format(i=i) for i in range(10)], "Topic":["topic{i}".format(i=i) for i in range(10)], "Return":[1,2,3,2,1,2,4,7,1,3]}df = pd.DataFrame.from_dict(data)dates = np.array(df["Date"].tolist())returns = np.array(df["Return"].tolist())# Calculate the minimas and the maximasminimas = (np.diff(np.sign(np.diff(returns))) > 0).nonzero()[0] + 1&nbsp;maximas = (np.diff(np.sign(np.diff(returns))) < 0).nonzero()[0] + 1# Plot the entire data firstplt.plot(dates, returns)# Then mark the maximas and the minimasfor minima in minimas:&nbsp; &nbsp; plt.plot(df.iloc[minima]["Date"], df.iloc[minima]["Return"], marker="o", label=str(df.iloc[minima]["Topic"]))for maxima in maximas:&nbsp; &nbsp; plt.plot(df.iloc[maxima]["Date"], df.iloc[maxima]["Return"], marker="o", label=str(df.iloc[maxima]["Topic"]))plt.legend()plt.show()示例数据框:&nbsp; &nbsp;Date&nbsp; &nbsp;Topic&nbsp; Return0&nbsp; date0&nbsp; topic0&nbsp; &nbsp; &nbsp; &nbsp;11&nbsp; date1&nbsp; topic1&nbsp; &nbsp; &nbsp; &nbsp;22&nbsp; date2&nbsp; topic2&nbsp; &nbsp; &nbsp; &nbsp;33&nbsp; date3&nbsp; topic3&nbsp; &nbsp; &nbsp; &nbsp;24&nbsp; date4&nbsp; topic4&nbsp; &nbsp; &nbsp; &nbsp;15&nbsp; date5&nbsp; topic5&nbsp; &nbsp; &nbsp; &nbsp;26&nbsp; date6&nbsp; topic6&nbsp; &nbsp; &nbsp; &nbsp;47&nbsp; date7&nbsp; topic7&nbsp; &nbsp; &nbsp; &nbsp;78&nbsp; date8&nbsp; topic8&nbsp; &nbsp; &nbsp; &nbsp;19&nbsp; date9&nbsp; topic9&nbsp; &nbsp; &nbsp; &nbsp;3绘制它产生:&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python