Skip to content

Commit 8fbe101

Browse files
authored
Fix to_dict and from_dict type stubs (#39)
* Update frame.pyi * - Added tests for both from_dict and to_dict * Added types to from_dict * Fix failing tests * Fix formatting
1 parent 08be184 commit 8fbe101

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

pandas-stubs/core/frame.pyi

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,13 @@ class DataFrame(NDFrame, OpsMixin):
206206
def __matmul__(self, other): ...
207207
def __rmatmul__(self, other): ...
208208
@classmethod
209-
def from_dict(cls, data, orient=..., dtype=..., columns=...) -> DataFrame: ...
209+
def from_dict(
210+
cls,
211+
data: Dict[Any, Any],
212+
orient: Literal["columns", "index", "tight"] = ...,
213+
dtype: _str = ...,
214+
columns: List[_str] = ...,
215+
) -> DataFrame: ...
210216
def to_numpy(
211217
self,
212218
dtype: Optional[Union[Type[DtypeNp], Dtype]] = ...,
@@ -222,7 +228,7 @@ class DataFrame(NDFrame, OpsMixin):
222228
@overload
223229
def to_dict(
224230
self,
225-
orient: Literal["dict", "list", "series", "split", "index"] = ...,
231+
orient: Literal["dict", "list", "series", "split", "tight", "index"] = ...,
226232
into: Hashable = ...,
227233
) -> Dict[_str, Any]: ...
228234
def to_gbq(

tests/test_frame.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -774,6 +774,19 @@ def test_types_resample() -> None:
774774
df.resample("20min", origin="epoch", offset=pd.Timedelta(2, "minutes"), on="date")
775775

776776

777+
def test_types_to_dict() -> None:
778+
data = pd.DataFrame({"a": [1], "b": [2]})
779+
data.to_dict(orient="records")
780+
data.to_dict(orient="dict")
781+
data.to_dict(orient="list")
782+
data.to_dict(orient="series")
783+
data.to_dict(orient="split")
784+
data.to_dict(orient="index")
785+
786+
# orient param accepting "tight" added in 1.4.0 https://pandas.pydata.org/docs/whatsnew/v1.4.0.html
787+
data.to_dict(orient="tight")
788+
789+
777790
def test_types_from_dict() -> None:
778791
pd.DataFrame.from_dict({"col_1": [3, 2, 1, 0], "col_2": ["a", "b", "c", "d"]})
779792
pd.DataFrame.from_dict({1: [3, 2, 1, 0], 2: ["a", "b", "c", "d"]})
@@ -783,6 +796,17 @@ def test_types_from_dict() -> None:
783796
pd.DataFrame.from_dict(
784797
data={"col_1": {"a": 1}, "col_2": {"a": 1, "b": 2}}, orient="columns"
785798
)
799+
# orient param accepting "tight" added in 1.4.0 https://pandas.pydata.org/docs/whatsnew/v1.4.0.html
800+
pd.DataFrame.from_dict(
801+
data={
802+
"index": [("a", "b"), ("a", "c")],
803+
"columns": [("x", 1), ("y", 2)],
804+
"data": [[1, 3], [2, 4]],
805+
"index_names": ["n1", "n2"],
806+
"column_names": ["z1", "z2"],
807+
},
808+
orient="tight",
809+
)
786810

787811

788812
def test_pipe() -> None:

0 commit comments

Comments
 (0)