在 Plotly Express 中使用 Pandas 索引 [英] Use Pandas index in Plotly Express

查看:114
本文介绍了在 Plotly Express 中使用 Pandas 索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Plotly Express 允许我轻松绘制 Pandas 数据框,如他们的示例中所述.我不想使用 x 的命名列和 y 的命名列,而是将数据框的索引用于 x,将命名列用于 y.

Plotly Express allows me to easily plot a pandas dataframe, as explained in their examples. Rather than using a named column for x and a named column for y, I would like to use the dataframe's index for x and a named column for y.

使用命名列的示例

import plotly.express as px
iris = px.data.iris()
fig = px.scatter(iris, x="sepal_width", y="sepal_length")
fig.show()

我想要什么(虚假示例)

import plotly.express as px
iris = px.data.iris()
fig = px.scatter(iris, x="index", y="sepal_length")
fig.show()

这显然会抛出:

ValueError: 'x' 的值不是 'data_frame' 中列的名称.应为 ['sepal_length', 'sepal_width', 'petal_length' 之一,'petal_width', 'species', 'species_id'] 但收到:index

ValueError: Value of 'x' is not the name of a column in 'data_frame'. Expected one of ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species', 'species_id'] but received: index

丑陋的修复

import plotly.express as px
iris = px.data.iris().reset_index()
fig = px.scatter(iris, x="index", y="sepal_length")
fig.show()

推荐答案

参考:https://plot.ly/python/px-arguments/#using-the-index-of-a-dataframe

您可以显式地将索引作为引用传递.

You can pass the index as reference explicitly.

所以在你的情况下,这将是:

So in your case, this would be:

import plotly.express as px
iris = px.data.iris()
fig = px.scatter(iris, x=iris.index, y="sepal_length")
fig.show()

--

额外问题:如果 iris 有一个 pd.MultiIndex 会怎样?

BONUS QUESTION: what if iris has a pd.MultiIndex?

使用pd.MultiIndex.get_level_values.

import plotly.express as px

# dummy example for multiindex
iris = px.data.iris().set_index(['species', 'species_id', iris.index])

fig = px.scatter(
   iris, 
   x=iris.index.get_level_values(2), 
   y="sepal_length"
)

fig.show()

这篇关于在 Plotly Express 中使用 Pandas 索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆