【问题标题】:Pandas Scatter Plot: Indices Out-of-BoundsPandas 散点图:索引越界
【发布时间】:2018-01-11 20:39:27
【问题描述】:

我有一个简单的 Pandas 数据框:

deltastart_hourend_hour都是numpy.int64

type(df.delta[0])
->numpy.int64

每当我尝试使用 Pandas 方法绘制散点图时,都会收到“IndexError: indices are out-of-bounds”。例如:

sc2 = df.plot.scatter(x=df.delta, y=df.start_hour)

产生:

IndexError Traceback (most recent call last) <ipython-input-118-4d521c29b97f> in <module>() ----> 1 sc2 = df.plot.scatter(x=df.delta, y=df.start_hour) ... /mnt/xarfuse/uid-116535/[edit]/pandas/core/indexing.pyc in maybe_convert_indices(indices, n) IndexError: indices are out-of-bounds

我也尝试过显式转换为 Numpy 数组,如 this post 中所述:

df_x = np.array(df['delta'].tolist())
df_y = np.array(df['start_hour'].tolist())
sc1 = df.plot.scatter(x=df_x, y=df_y)

产生同样的错误。

我确定我错过了一些真的简单的东西。感谢您的帮助!

【问题讨论】:

    标签: python pandas numpy plot scatter


    【解决方案1】:

    当您将 df['delta'] 传递给 x 时,它会像 df[df['delta']] 一样返回 key error : not in index,因此您只需将列名作为 x 和 y 值传递给 scatter 方法,即

    sc2 = df.plot.scatter(x='delta', y='start_hour')
    

    例子

    df = pd.DataFrame({'delta':[162,9,9,38,691,58],'start_hour':[1,5,11,1,7,6],'last_hour':[3,5,11,2,19,7]})
    sc2 = df.plot.scatter(x='delta', y='start_hour')
    plt.show()
    

    如果你想传递 numpy 数组,那么不要在 df 中搜索它。即直接使用plt.scatter 例如

    df_x = np.array(df['delta'].tolist())
    df_y = np.array(df['start_hour'].tolist())
    plt.scatter(x=df_x, y=df_y)
    plt.show() 
    

    希望对你有帮助

    【讨论】:

    • 谢谢!这确实解决了问题!
    猜你喜欢
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 2016-03-09
    • 2014-06-06
    • 2013-07-27
    • 2015-03-22
    相关资源
    最近更新 更多