【问题标题】:ValueError: invalid literal for float(): when adding annotation in pandasValueError:float()的无效文字:在熊猫中添加注释时
【发布时间】:2017-10-13 08:00:09
【问题描述】:

当我尝试向我的绘图添加注释时出现此错误 - ValueError: invalid literal for float(): 10_May

我的数据框:

我的代码(我在绘图之前使用to_datetimestrftime,因为我需要对存储为字符串的日期进行排序):

# 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[] 访问它。感谢您的建议。

【问题讨论】:

    标签: python-2.7 pandas matplotlib dataframe jupyter


    【解决方案1】:

    对我来说,首先绘图,然后通过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='-|>'))
    

    编辑:

    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='-|>'))
    

    【讨论】:

    • 超级好,周末愉快!
    猜你喜欢
    • 2013-01-15
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 2019-01-12
    • 2022-12-12
    相关资源
    最近更新 更多