【问题标题】:ValueError: Could not interpret input 'index' when using index with seaborn lineplotValueError:使用带有 seaborn 线图的索引时无法解释输入“索引”
【发布时间】:2019-02-14 20:05:46
【问题描述】:

我希望使用 pandas DataFrame 的索引作为 seaborn 图的 x 值。但是,这会引发值错误。

一个小测试示例:

import pandas as pd
import seaborn as sns
sns.lineplot(x='index',y='test',hue='test2',data=pd.DataFrame({'test':range(9),'test2':range(9)}))

它引发:

ValueError: Could not interpret input 'index'

不能将索引用作 x 值吗?我究竟做错了什么? Python 2.7,海生 0.9

【问题讨论】:

    标签: python python-2.7 pandas seaborn


    【解决方案1】:

    我宁愿以这种方式使用它。您需要删除hue,因为我认为它有不同的用途,不适用于您当前的DataFrame,因为您只有一行。访问官方文档here 了解更多信息。

    df=pd.DataFrame({'test':range(9),'test2':range(9)})
    sns.lineplot(x=df.index, y='test', data=df)
    

    输出

    【讨论】:

    【解决方案2】:

    您需要确保提供给x 参数的字符串实际上是数据框中的。最简单的解决方案是重置数据框的索引以将索引转换为列。

    sns.lineplot(x='index', y='test', data=pd.DataFrame({'test':range(9),'test2':range(9)}).reset_index())
    

    【讨论】:

      【解决方案3】:

      我知道这是一个老问题,也许当时还不存在,但有一种更简单的方法可以实现这一点:

      如果您只是将数据帧中的一个系列作为“数据”参数传递,seaborn 将自动使用索引作为 x 值。

      sns.lineplot(data=df.column1)
      

      【讨论】:

        猜你喜欢
        • 2020-11-15
        • 2019-01-12
        • 2013-07-07
        • 1970-01-01
        • 2010-12-13
        • 1970-01-01
        • 2020-10-18
        • 2018-12-16
        • 2021-08-01
        相关资源
        最近更新 更多