Skip to content

Commit 4ab7bb4

Browse files
authored
DOC: Fixed example section in pandas/core/dtypes/*.py (#31451)
1 parent 625441b commit 4ab7bb4

File tree

7 files changed

+64
-45
lines changed

7 files changed

+64
-45
lines changed

ci/code_checks.sh

+4
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,10 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
305305
pandas/core/arrays/boolean.py
306306
RET=$(($RET + $?)) ; echo $MSG "DONE"
307307

308+
MSG='Doctests dtypes'; echo $MSG
309+
pytest -q --doctest-modules pandas/core/dtypes/
310+
RET=$(($RET + $?)) ; echo $MSG "DONE"
311+
308312
MSG='Doctests arrays/boolean.py' ; echo $MSG
309313
pytest -q --doctest-modules pandas/core/arrays/boolean.py
310314
RET=$(($RET + $?)) ; echo $MSG "DONE"

pandas/core/dtypes/base.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
"""Extend pandas with custom array types"""
1+
"""
2+
Extend pandas with custom array types.
3+
"""
4+
25
from typing import Any, List, Optional, Tuple, Type
36

47
import numpy as np
@@ -231,8 +234,9 @@ def construct_from_string(cls, string: str):
231234
... if match:
232235
... return cls(**match.groupdict())
233236
... else:
234-
... raise TypeError(f"Cannot construct a '{cls.__name__}' from
235-
... " "'{string}'")
237+
... raise TypeError(
238+
... f"Cannot construct a '{cls.__name__}' from '{string}'"
239+
... )
236240
"""
237241
if not isinstance(string, str):
238242
raise TypeError(

pandas/core/dtypes/cast.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
""" routings for casting """
1+
"""
2+
Routines for casting.
3+
"""
24

35
from datetime import date, datetime, timedelta
46

@@ -269,12 +271,12 @@ def maybe_upcast_putmask(result: np.ndarray, mask: np.ndarray, other):
269271
270272
Examples
271273
--------
272-
>>> result, _ = maybe_upcast_putmask(np.arange(1,6),
273-
np.array([False, True, False, True, True]), np.arange(21,23))
274+
>>> arr = np.arange(1, 6)
275+
>>> mask = np.array([False, True, False, True, True])
276+
>>> result, _ = maybe_upcast_putmask(arr, mask, False)
274277
>>> result
275-
array([1, 21, 3, 22, 21])
278+
array([1, 0, 3, 0, 0])
276279
"""
277-
278280
if not isinstance(result, np.ndarray):
279281
raise ValueError("The result input must be a ndarray.")
280282
if not is_scalar(other):
@@ -662,9 +664,8 @@ def infer_dtype_from_array(arr, pandas_dtype: bool = False):
662664
array(['1', '1'], dtype='<U21')
663665
664666
>>> infer_dtype_from_array([1, '1'])
665-
(numpy.object_, [1, '1'])
667+
(<class 'numpy.object_'>, [1, '1'])
666668
"""
667-
668669
if isinstance(arr, np.ndarray):
669670
return arr.dtype, arr
670671

@@ -709,7 +710,7 @@ def maybe_infer_dtype_type(element):
709710
>>> from collections import namedtuple
710711
>>> Foo = namedtuple("Foo", "dtype")
711712
>>> maybe_infer_dtype_type(Foo(np.dtype("i8")))
712-
numpy.int64
713+
dtype('int64')
713714
"""
714715
tipo = None
715716
if hasattr(element, "dtype"):
@@ -1555,8 +1556,8 @@ def maybe_cast_to_integer_array(arr, dtype, copy: bool = False):
15551556
15561557
Returns
15571558
-------
1558-
int_arr : ndarray
1559-
An array of integer or unsigned integer dtype
1559+
ndarray
1560+
Array of integer or unsigned integer dtype.
15601561
15611562
Raises
15621563
------
@@ -1567,19 +1568,18 @@ def maybe_cast_to_integer_array(arr, dtype, copy: bool = False):
15671568
--------
15681569
If you try to coerce negative values to unsigned integers, it raises:
15691570
1570-
>>> Series([-1], dtype="uint64")
1571+
>>> pd.Series([-1], dtype="uint64")
15711572
Traceback (most recent call last):
15721573
...
15731574
OverflowError: Trying to coerce negative values to unsigned integers
15741575
15751576
Also, if you try to coerce float values to integers, it raises:
15761577
1577-
>>> Series([1, 2, 3.5], dtype="int64")
1578+
>>> pd.Series([1, 2, 3.5], dtype="int64")
15781579
Traceback (most recent call last):
15791580
...
15801581
ValueError: Trying to coerce float values to integers
15811582
"""
1582-
15831583
try:
15841584
if not hasattr(arr, "astype"):
15851585
casted = np.array(arr, dtype=dtype, copy=copy)

pandas/core/dtypes/common.py

+15-16
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
""" common type operations """
1+
"""
2+
Common type operations.
3+
"""
4+
25
from typing import Any, Callable, Union
36
import warnings
47

@@ -705,7 +708,7 @@ def is_dtype_equal(source, target) -> bool:
705708
False
706709
>>> is_dtype_equal(CategoricalDtype(), "category")
707710
True
708-
>>> is_dtype_equal(DatetimeTZDtype(), "datetime64")
711+
>>> is_dtype_equal(DatetimeTZDtype(tz="UTC"), "datetime64")
709712
False
710713
"""
711714

@@ -862,7 +865,7 @@ def is_signed_integer_dtype(arr_or_dtype) -> bool:
862865
True
863866
>>> is_signed_integer_dtype('Int8')
864867
True
865-
>>> is_signed_dtype(pd.Int8Dtype)
868+
>>> is_signed_integer_dtype(pd.Int8Dtype)
866869
True
867870
>>> is_signed_integer_dtype(np.datetime64)
868871
False
@@ -994,7 +997,7 @@ def is_datetime64_any_dtype(arr_or_dtype) -> bool:
994997
995998
Returns
996999
-------
997-
boolean
1000+
bool
9981001
Whether or not the array or dtype is of the datetime64 dtype.
9991002
10001003
Examples
@@ -1011,13 +1014,11 @@ def is_datetime64_any_dtype(arr_or_dtype) -> bool:
10111014
False
10121015
>>> is_datetime64_any_dtype(np.array([1, 2]))
10131016
False
1014-
>>> is_datetime64_any_dtype(np.array([], dtype=np.datetime64))
1017+
>>> is_datetime64_any_dtype(np.array([], dtype="datetime64[ns]"))
10151018
True
1016-
>>> is_datetime64_any_dtype(pd.DatetimeIndex([1, 2, 3],
1017-
dtype=np.datetime64))
1019+
>>> is_datetime64_any_dtype(pd.DatetimeIndex([1, 2, 3], dtype="datetime64[ns]"))
10181020
True
10191021
"""
1020-
10211022
if arr_or_dtype is None:
10221023
return False
10231024
return is_datetime64_dtype(arr_or_dtype) or is_datetime64tz_dtype(arr_or_dtype)
@@ -1034,7 +1035,7 @@ def is_datetime64_ns_dtype(arr_or_dtype) -> bool:
10341035
10351036
Returns
10361037
-------
1037-
boolean
1038+
bool
10381039
Whether or not the array or dtype is of the datetime64[ns] dtype.
10391040
10401041
Examples
@@ -1051,16 +1052,13 @@ def is_datetime64_ns_dtype(arr_or_dtype) -> bool:
10511052
False
10521053
>>> is_datetime64_ns_dtype(np.array([1, 2]))
10531054
False
1054-
>>> is_datetime64_ns_dtype(np.array([], dtype=np.datetime64)) # no unit
1055+
>>> is_datetime64_ns_dtype(np.array([], dtype="datetime64")) # no unit
10551056
False
1056-
>>> is_datetime64_ns_dtype(np.array([],
1057-
dtype="datetime64[ps]")) # wrong unit
1057+
>>> is_datetime64_ns_dtype(np.array([], dtype="datetime64[ps]")) # wrong unit
10581058
False
1059-
>>> is_datetime64_ns_dtype(pd.DatetimeIndex([1, 2, 3],
1060-
dtype=np.datetime64)) # has 'ns' unit
1059+
>>> is_datetime64_ns_dtype(pd.DatetimeIndex([1, 2, 3], dtype="datetime64[ns]"))
10611060
True
10621061
"""
1063-
10641062
if arr_or_dtype is None:
10651063
return False
10661064
try:
@@ -1240,7 +1238,8 @@ def is_datetimelike_v_numeric(a, b):
12401238
12411239
Examples
12421240
--------
1243-
>>> dt = np.datetime64(pd.datetime(2017, 1, 1))
1241+
>>> from datetime import datetime
1242+
>>> dt = np.datetime64(datetime(2017, 1, 1))
12441243
>>>
12451244
>>> is_datetimelike_v_numeric(1, 1)
12461245
False

pandas/core/dtypes/concat.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""
2-
Utility functions related to concat
2+
Utility functions related to concat.
33
"""
44

55
import numpy as np
@@ -261,6 +261,8 @@ def union_categoricals(
261261
>>> a = pd.Categorical(["a", "b"], ordered=True)
262262
>>> b = pd.Categorical(["a", "b", "c"], ordered=True)
263263
>>> union_categoricals([a, b])
264+
Traceback (most recent call last):
265+
...
264266
TypeError: to union ordered Categoricals, all categories must be the same
265267
266268
New in version 0.20.0

pandas/core/dtypes/dtypes.py

+18-11
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
""" define extension dtypes """
1+
"""
2+
Define extension dtypes.
3+
"""
4+
25
import re
36
from typing import Any, Dict, List, MutableMapping, Optional, Tuple, Type, Union, cast
47

@@ -286,23 +289,27 @@ def _from_values_or_dtype(
286289
287290
Examples
288291
--------
289-
>>> CategoricalDtype._from_values_or_dtype()
292+
>>> pd.CategoricalDtype._from_values_or_dtype()
290293
CategoricalDtype(categories=None, ordered=None)
291-
>>> CategoricalDtype._from_values_or_dtype(categories=['a', 'b'],
292-
... ordered=True)
294+
>>> pd.CategoricalDtype._from_values_or_dtype(
295+
... categories=['a', 'b'], ordered=True
296+
... )
293297
CategoricalDtype(categories=['a', 'b'], ordered=True)
294-
>>> dtype1 = CategoricalDtype(['a', 'b'], ordered=True)
295-
>>> dtype2 = CategoricalDtype(['x', 'y'], ordered=False)
296-
>>> c = Categorical([0, 1], dtype=dtype1, fastpath=True)
297-
>>> CategoricalDtype._from_values_or_dtype(c, ['x', 'y'], ordered=True,
298-
... dtype=dtype2)
298+
>>> dtype1 = pd.CategoricalDtype(['a', 'b'], ordered=True)
299+
>>> dtype2 = pd.CategoricalDtype(['x', 'y'], ordered=False)
300+
>>> c = pd.Categorical([0, 1], dtype=dtype1, fastpath=True)
301+
>>> pd.CategoricalDtype._from_values_or_dtype(
302+
... c, ['x', 'y'], ordered=True, dtype=dtype2
303+
... )
304+
Traceback (most recent call last):
305+
...
299306
ValueError: Cannot specify `categories` or `ordered` together with
300307
`dtype`.
301308
302309
The supplied dtype takes precedence over values' dtype:
303310
304-
>>> CategoricalDtype._from_values_or_dtype(c, dtype=dtype2)
305-
CategoricalDtype(['x', 'y'], ordered=False)
311+
>>> pd.CategoricalDtype._from_values_or_dtype(c, dtype=dtype2)
312+
CategoricalDtype(categories=['x', 'y'], ordered=False)
306313
"""
307314
from pandas.core.dtypes.common import is_categorical
308315

pandas/core/dtypes/inference.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,8 @@ def is_file_like(obj) -> bool:
117117
118118
Examples
119119
--------
120-
>>> buffer(StringIO("data"))
120+
>>> import io
121+
>>> buffer = io.StringIO("data")
121122
>>> is_file_like(buffer)
122123
True
123124
>>> is_file_like([1, 2, 3])
@@ -311,6 +312,7 @@ def is_named_tuple(obj) -> bool:
311312
312313
Examples
313314
--------
315+
>>> from collections import namedtuple
314316
>>> Point = namedtuple("Point", ["x", "y"])
315317
>>> p = Point(1, 2)
316318
>>>
@@ -339,6 +341,7 @@ def is_hashable(obj) -> bool:
339341
340342
Examples
341343
--------
344+
>>> import collections
342345
>>> a = ([],)
343346
>>> isinstance(a, collections.abc.Hashable)
344347
True

0 commit comments

Comments
 (0)