Skip to content

Fix to_dict and from_dict type stubs #39

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

Merged
merged 6 commits into from
Jul 19, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
10 changes: 8 additions & 2 deletions pandas-stubs/core/frame.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,13 @@ class DataFrame(NDFrame, OpsMixin):
def __matmul__(self, other): ...
def __rmatmul__(self, other): ...
@classmethod
def from_dict(cls, data, orient=..., dtype=..., columns=...) -> DataFrame: ...
def from_dict(
cls,
data: Dict[Any, Any],
orient: Literal["columns", "index", "tight"] = ...,
dtype: _str = ...,
columns: List[_str] = ...,
) -> DataFrame: ...
def to_numpy(
self,
dtype: Optional[Union[Type[DtypeNp], Dtype]] = ...,
Expand All @@ -226,7 +232,7 @@ class DataFrame(NDFrame, OpsMixin):
@overload
def to_dict(
self,
orient: Literal["dict", "list", "series", "split", "index"] = ...,
orient: Literal["dict", "list", "series", "split", "tight", "index"] = ...,
into: Hashable = ...,
) -> Dict[_str, Any]: ...
def to_gbq(
Expand Down
24 changes: 24 additions & 0 deletions tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,19 @@ def test_types_resample() -> None:
df.resample("20min", origin="epoch", offset=pd.Timedelta(2, "minutes"), on="date")


def test_types_to_dict() -> None:
data = pd.DataFrame({"a": [1], "b": [2]})
data.to_dict(orient="records")
data.to_dict(orient="dict")
data.to_dict(orient="list")
data.to_dict(orient="series")
data.to_dict(orient="split")
data.to_dict(orient="index")

# orient param accepting "tight" added in 1.4.0 https://pandas.pydata.org/docs/whatsnew/v1.4.0.html
data.to_dict(orient="tight")


def test_types_from_dict() -> None:
pd.DataFrame.from_dict({"col_1": [3, 2, 1, 0], "col_2": ["a", "b", "c", "d"]})
pd.DataFrame.from_dict({1: [3, 2, 1, 0], 2: ["a", "b", "c", "d"]})
Expand All @@ -778,6 +791,17 @@ def test_types_from_dict() -> None:
pd.DataFrame.from_dict(
data={"col_1": {"a": 1}, "col_2": {"a": 1, "b": 2}}, orient="columns"
)
# orient param accepting "tight" added in 1.4.0 https://pandas.pydata.org/docs/whatsnew/v1.4.0.html
pd.DataFrame.from_dict(
data={
"index": [("a", "b"), ("a", "c")],
"columns": [("x", 1), ("y", 2)],
"data": [[1, 3], [2, 4]],
"index_names": ["n1", "n2"],
"column_names": ["z1", "z2"],
},
orient="tight",
)


def test_pipe() -> None:
Expand Down