【问题标题】:How to use Polars with Plotly without converting to Pandas?如何在不转换为 Pandas 的情况下将 Polars 与 Plotly 一起使用?
【发布时间】:2023-01-04 00:05:56
【问题描述】:

我想用 Polars 替换 Pandas,但我无法找到如何在不转换为 Pandas 的情况下将 Polars 与 Plotly 一起使用。我想知道是否有办法将 Pandas 完全排除在流程之外。

考虑以下测试数据:

import polars as pl
import numpy as np
import plotly.express as px

df = pl.DataFrame(
    {
        "nrs": [1, 2, 3, None, 5],
        "names": ["foo", "ham", "spam", "egg", None],
        "random": np.random.rand(5),
        "groups": ["A", "A", "B", "C", "B"],
    }
)

fig = px.bar(df, x='names', y='random')
fig.show()

我希望此代码在 Jupyter 笔记本中显示条形图,但它返回错误:

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/polars/internals/frame.py:1483: UserWarning: accessing series as Attribute of a DataFrame is deprecated
  warnings.warn("accessing series as Attribute of a DataFrame is deprecated")

可以使用 df = df.to_pandas() 将 Polars 数据帧转换为 Pandas 数据帧。然后,它起作用了。但是,是否有另一种更简单、更优雅的解决方案?

【问题讨论】:

    标签: python plotly-python python-polars


    【解决方案1】:

    是的,不需要 Pandas 参与。有人 (sa-) 请求支持更好的选项 here 并提供了解决方法。

    “我现在使用的解决方法是 px.line(x=df["a"], y=df["b"]),但如果数据框的名称太大,它会变得笨拙”

    解决方法中包含的示例更简单。
    对于 OP 的代码示例,我发现除了使用 px.bar(df, x=df["names"], y=df["random"]) 指定数据框列外,还可以强制转换为列表:

    import polars as pl
    import numpy as np
    import plotly.express as px
    
    df = pl.DataFrame(
        {
            "nrs": [1, 2, 3, None, 5],
            "names": ["foo", "ham", "spam", "egg", None],
            "random": np.random.rand(5),
            "groups": ["A", "A", "B", "C", "B"],
        }
    )
    
    px.bar(df, x=list(df["names"]), y=list(df["random"]))
    

    更好地了解极地,一旦您看到解决方法的想法,您可能会看到一些其他选项。

    there 发布的示例更简单,您可以使用 px.line(x=df["a"], y=df["b"],而不是像您可以用于 Pandas 数据框的 px.line(df, x="a", y="b")。对于极坐标,即:

    import polars as pl
    import plotly.express as px
    
    df = pl.DataFrame({"a":[1,2,3,4,5], "b":[1,4,9,16,25]})
    
    px.line(x=df["a"], y=df["b"])
    

    【讨论】:

    • 这正是我所希望的优雅解决方案。谢谢!
    猜你喜欢
    • 2023-01-19
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多