gpt4 book ai didi

python-3.x - 使用 'for' 循环为 df 中的每一列创建 Plotly 图

转载 作者:行者123 更新时间:2023-12-04 09:04:48 25 4
gpt4 key购买 nike

我想使用 for 在 df 中制作多个 Plotly Scatter 图(每列一个) Python 中的循环。我还希望能够通过输入列名来显示图。
查看示例代码:

import plotly.express as px
import pandas as pd

df = pd.DataFrame({'A': [3, 1, 2, 3],
'B': [5, 6, 7, 8],
'C': [2, 1, 6, 3]})
df

A B C
0 3 5 2
1 1 6 1
2 2 7 6
3 3 8 3
我得到的最接近的是这个:
for i in df.columns:
i = px.scatter(df,
x="A",
y=i)
但这无法为每个图分配一个值。我希望能够通过输入 A 来显示 A 列的图,通过输入 B 来显示 B 的图,等等。

最佳答案

您可以将图添加到像这样的字典

plots = {i: px.scatter(df, x="A", y=i) for i in df.columns}
相当于但短于
plots = {}
for i in df.columns:
plots[i] = px.scatter(df, x="A", y=i)
然后你可以用 plots['A'] 显示每个图, plots['B']plots['C']

关于python-3.x - 使用 'for' 循环为 df 中的每一列创建 Plotly 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63467762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com