ValueError:将索引与seaborn线图一起使用时,无法解释输入“索引”

时间:2018-09-10 11:33:46

标签: python python-2.7 pandas seaborn

我想使用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,seaborn 0.9

3 个答案:

答案 0 :(得分:3)

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

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

输出

enter image description here

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

我知道这是一个老问题,也许当时还没有这个问题,但有一个更简单的方法来实现这一点:

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

sns.lineplot(data=df.column1)