Skip to content

Commit

Permalink
DOC: document internal methods in types/common.py
Browse files Browse the repository at this point in the history
Partially addresses gh-15895.
  • Loading branch information
gfyoung committed Apr 7, 2017
1 parent d9e00d2 commit 2b19fc8
Showing 1 changed file with 131 additions and 15 deletions.
146 changes: 131 additions & 15 deletions pandas/types/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,20 @@


def _ensure_float(arr):
"""
Ensure that an array object has a float dtype if possible.
Parameters
----------
arr : ndarray, Series
The array whose data type we want to enforce as float.
Returns
-------
float_arr : The original array cast to the float dtype if
possible. Otherwise, the original array is returned.
"""

if issubclass(arr.dtype.type, (np.integer, np.bool_)):
arr = arr.astype(float)
return arr
Expand All @@ -46,6 +60,20 @@ def _ensure_float(arr):


def _ensure_categorical(arr):
"""
Ensure that an array-like object is a Categorical (if not already).
Parameters
----------
arr : array-like
The array that we want to convert into a Categorical.
Returns
-------
cat_arr : The original array cast as a Categorical. If it already
is a Categorical, we return as is.
"""

if not is_categorical(arr):
from pandas import Categorical
arr = Categorical(arr)
Expand Down Expand Up @@ -220,10 +248,22 @@ def is_datetime_or_timedelta_dtype(arr_or_dtype):

def _is_unorderable_exception(e):
"""
return a boolean if we an unorderable exception error message
Check if the exception raised is an unorderable exception.
The error message differs for 3 <= PY <= 3.5 and PY >= 3.6, so
we need to condition based on Python version.
Parameters
----------
e : Exception or sub-class
The exception object to check.
These are different error message for PY>=3<=3.5 and PY>=3.6
Returns
-------
is_orderable_exc : Whether or not the exception raised is an
unorderable exception.
"""

if PY36:
return "'>' not supported between instances of" in str(e)

Expand Down Expand Up @@ -346,7 +386,22 @@ def is_complex_dtype(arr_or_dtype):


def _coerce_to_dtype(dtype):
""" coerce a string / np.dtype to a dtype """
"""
Coerce a string or np.dtype to a pandas or numpy
dtype if possible.
If we cannot convert to a pandas dtype initially,
we convert to a numpy dtype.
Parameters
----------
dtype : The dtype that we want to coerce.
Returns
-------
pd_or_np_dtype : The coerced dtype.
"""

if is_categorical_dtype(dtype):
dtype = CategoricalDtype()
elif is_datetime64tz_dtype(dtype):
Expand All @@ -359,8 +414,27 @@ def _coerce_to_dtype(dtype):


def _get_dtype(arr_or_dtype):
"""
Get the dtype instance associated with an array
or dtype object.
Parameters
----------
arr_or_dtype : ndarray, Series, dtype, type
The array-like or dtype object whose dtype we want to extract.
Returns
-------
obj_dtype : The extract dtype instance from the
passed in array or dtype object.
Raises
------
TypeError : The passed in object is None.
"""

if arr_or_dtype is None:
raise TypeError
raise TypeError("Cannot deduce dtype from null object")
if isinstance(arr_or_dtype, np.dtype):
return arr_or_dtype
elif isinstance(arr_or_dtype, type):
Expand All @@ -385,6 +459,21 @@ def _get_dtype(arr_or_dtype):


def _get_dtype_type(arr_or_dtype):
"""
Get the type (NOT dtype) instance associated with
an array or dtype object.
Parameters
----------
arr_or_dtype : ndarray, Series, dtype, type
The array-like or dtype object whose type we want to extract.
Returns
-------
obj_type : The extract type instance from the
passed in array or dtype object.
"""

if isinstance(arr_or_dtype, np.dtype):
return arr_or_dtype.type
elif isinstance(arr_or_dtype, type):
Expand All @@ -410,16 +499,27 @@ def _get_dtype_type(arr_or_dtype):


def _get_dtype_from_object(dtype):
"""Get a numpy dtype.type-style object. This handles the datetime64[ns]
and datetime64[ns, TZ] compat
"""
Get a numpy dtype.type-style object for a dtype object.
This methods also includes handling of the datetime64[ns] and
datetime64[ns, TZ] objects.
If no dtype can be found, we return ``object``.
Parameters
----------
dtype : dtype, type
The dtype object whose numpy dtype.type-style
object we want to extract.
Notes
-----
If nothing can be found, returns ``object``.
Returns
-------
dtype_object : The extracted numpy dtype.type-style object.
"""

# type object from a dtype
if isinstance(dtype, type) and issubclass(dtype, np.generic):
# Type object from a dtype
return dtype
elif is_categorical(dtype):
return CategoricalDtype().type
Expand All @@ -429,7 +529,7 @@ def _get_dtype_from_object(dtype):
try:
_validate_date_like_dtype(dtype)
except TypeError:
# should still pass if we don't have a datelike
# Should still pass if we don't have a date-like
pass
return dtype.type
elif isinstance(dtype, string_types):
Expand All @@ -444,17 +544,33 @@ def _get_dtype_from_object(dtype):
try:
return _get_dtype_from_object(getattr(np, dtype))
except (AttributeError, TypeError):
# handles cases like _get_dtype(int)
# i.e., python objects that are valid dtypes (unlike user-defined
# types, in general)
# TypeError handles the float16 typecode of 'e'
# Handles cases like _get_dtype(int) i.e.,
# Python objects that are valid dtypes
# (unlike user-defined types, in general)
#
# TypeError handles the float16 type code of 'e'
# further handle internal types
pass

return _get_dtype_from_object(np.dtype(dtype))


def _validate_date_like_dtype(dtype):
"""
Check whether the dtype is a date-like dtype. Raises an error if invalid.
Parameters
----------
dtype : dtype, type
The dtype to check.
Raises
------
TypeError : The dtype could not be casted to a date-like dtype.
ValueError : The dtype is an illegal date-like dtype (e.g. the
the frequency provided is too specific)
"""

try:
typ = np.datetime_data(dtype)[0]
except ValueError as e:
Expand Down

0 comments on commit 2b19fc8

Please sign in to comment.