【问题标题】:Scatter plot form dataframe with index on x-axis来自数据帧的散点图,x 轴上有索引
【发布时间】:2018-09-24 20:51:51
【问题描述】:

我有 pandas DataFramedfindex 命名为 date 和列 columnAcolumnBcolumnC

我正在尝试使用 DataFrame 语法在 x 轴上散点图 index 和在 y 轴上散点图 columnA

当我尝试时:

df.plot(kind='scatter', x='date', y='columnA')

我收到错误 KeyError: 'date' 可能是因为 date 不是列

df.plot(kind='scatter', y='columnA')

我收到一个错误:

ValueError: scatter requires and x and y column

所以在 x 轴上没有默认索引。

df.plot(kind='scatter', x=df.index, y='columnA')

我遇到错误

KeyError: "DatetimeIndex(['1818-01-01', '1818-01-02', '1818-01-03', '1818-01-04',\n
                          '1818-01-05', '1818-01-06', '1818-01-07', '1818-01-08',\n
                          '1818-01-09', '1818-01-10',\n               ...\n  
                          '2018-03-22', '2018-03-23', '2018-03-24', '2018-03-25',\n
                          '2018-03-26', '2018-03-27', '2018-03-28', '2018-03-29',\n 
                          '2018-03-30', '2018-03-31'],\n  
dtype='datetime64[ns]', name='date', length=73139, freq=None) not in index"

如果我直接使用matplotlib.pyplot,我可以绘制它

plt.scatter(df.index, df['columnA'])

有没有办法使用DataFrame kind 语法将索引绘制为x-axis

【问题讨论】:

标签: python pandas matplotlib


【解决方案1】:

这有点难看(我认为您在问题中使用的 matplotlib 解决方案更好,FWIW),但您始终可以使用索引创建一个临时 DataFrame 作为列使用

df.reset_index()

如果索引是无名的,则默认名称为'index'。假设是这种情况,您可以使用

df.reset_index().plot(kind='scatter', x='index', y='columnA')

【讨论】:

  • 很高兴知道,谢谢。我想我知道为什么不能开箱即用。我用index 做散点图没有多大意义,因为索引应该是唯一的。就我而言,最好使用垃圾箱。
  • @Kocur4d 谢谢。仅供参考:索引 not 必须是唯一的:pd.DataFrame({'a': [1, 2]}, index=[1, 1]) 很好。我怀疑 Pandas 中缺乏对索引散点图的支持更多的是疏忽。
【解决方案2】:

一个更简单的解决方案是:

df['x1'] = df.index
df.plot(kind='scatter', x='x1', y='columnA')

只需在绘图语句之外创建索引变量。

【讨论】:

  • 我直接坐在x=df.index,所以我可以摆脱这个解决方案提供的错误。但在大多数情况下,我发现这个答案是正确的。
  • 是的,我回来看看这个。我同意df.plot(kind='scatter', x=df.index, y='columnA') 更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-25
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
相关资源
最近更新 更多