Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support dataframe interchange protocol #4244

Merged
merged 17 commits into from
Jun 30, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion packages/python/plotly/plotly/express/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from _plotly_utils.basevalidators import ColorscaleValidator
from plotly.colors import qualitative, sequential
import math
from packaging import version
import pandas as pd
import numpy as np

Expand Down Expand Up @@ -1307,7 +1308,15 @@ def build_dataframe(args, constructor):
# Cast data_frame argument to DataFrame (it could be a numpy array, dict etc.)
df_provided = args["data_frame"] is not None
if df_provided and not isinstance(args["data_frame"], pd.DataFrame):
if hasattr(args["data_frame"], "to_pandas"):
if hasattr(args["data_frame"], "__dataframe__") and version.parse(
pd.__version__
) >= version.parse("2.0.2"):
import pandas.api.interchange

df_not_pandas = args["data_frame"]
df_pandas = pandas.api.interchange.from_dataframe(df_not_pandas)
args["data_frame"] = df_pandas
elif hasattr(args["data_frame"], "to_pandas"):
args["data_frame"] = args["data_frame"].to_pandas()
else:
args["data_frame"] = pd.DataFrame(args["data_frame"])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,24 @@
import numpy as np
import pandas as pd
import pytest
import unittest.mock as mock
from plotly.express._core import build_dataframe
from pandas.testing import assert_frame_equal

# Fixtures
# --------
@pytest.fixture
def add_interchange_module_for_old_pandas():
if not hasattr(pd.api, "interchange"):
pd.api.interchange = mock.MagicMock()
# to make the following import work: `import pandas.api.interchange`
with mock.patch.dict(
"sys.modules", {"pandas.api.interchange": pd.api.interchange}
):
yield
else:
yield


def test_numpy():
fig = px.scatter(x=[1, 2, 3], y=[2, 3, 4], color=[1, 3, 9])
Expand Down Expand Up @@ -233,6 +248,26 @@ def test_build_df_with_index():
assert_frame_equal(tips.reset_index()[out["data_frame"].columns], out["data_frame"])


def test_build_df_using_interchange_protocol_mock(
add_interchange_module_for_old_pandas,
):
class CustomDataFrame:
def __dataframe__(self):
pass

input_dataframe = CustomDataFrame()
args = dict(data_frame=input_dataframe, x="petal_width", y="sepal_length")

iris_pandas = px.data.iris()

with mock.patch("pandas.__version__", "2.0.2"):
with mock.patch(
"pandas.api.interchange.from_dataframe", return_value=iris_pandas
) as mock_from_dataframe:
build_dataframe(args, go.Scatter)
mock_from_dataframe.assert_called_once_with(input_dataframe)


def test_timezones():
df = pd.DataFrame({"date": ["2015-04-04 19:31:30+1:00"], "value": [3]})
df["date"] = pd.to_datetime(df["date"])
Expand Down