Skip to content

CLN: Assorted cleanups #27632

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 2 commits into from
Jul 29, 2019
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
11 changes: 4 additions & 7 deletions pandas/core/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class PandasDelegate:
"""

def _delegate_property_get(self, name, *args, **kwargs):
raise TypeError("You cannot access the " "property {name}".format(name=name))
raise TypeError("You cannot access the property {name}".format(name=name))

def _delegate_property_set(self, name, value, *args, **kwargs):
raise TypeError("The property {name} cannot be set".format(name=name))
Expand Down Expand Up @@ -271,8 +271,7 @@ def plot(self):
@Appender(
_doc
% dict(
klass="DataFrame",
others=("register_series_accessor, " "register_index_accessor"),
klass="DataFrame", others=("register_series_accessor, register_index_accessor")
)
)
def register_dataframe_accessor(name):
Expand All @@ -284,8 +283,7 @@ def register_dataframe_accessor(name):
@Appender(
_doc
% dict(
klass="Series",
others=("register_dataframe_accessor, " "register_index_accessor"),
klass="Series", others=("register_dataframe_accessor, register_index_accessor")
)
)
def register_series_accessor(name):
Expand All @@ -297,8 +295,7 @@ def register_series_accessor(name):
@Appender(
_doc
% dict(
klass="Index",
others=("register_dataframe_accessor, " "register_series_accessor"),
klass="Index", others=("register_dataframe_accessor, register_series_accessor")
)
)
def register_index_accessor(name):
Expand Down
15 changes: 5 additions & 10 deletions pandas/core/arrays/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,17 @@
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
from pandas.util._decorators import Appender, Substitution
from pandas.util._validators import validate_fillna_kwargs

from pandas.core.dtypes.common import is_list_like
from pandas.core.dtypes.common import is_array_like, is_list_like
from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.dtypes.generic import ABCExtensionArray, ABCIndexClass, ABCSeries
from pandas.core.dtypes.missing import isna

from pandas._typing import ArrayLike
from pandas.core import ops
from pandas.core.algorithms import _factorize_array, unique
from pandas.core.missing import backfill_1d, pad_1d
from pandas.core.sorting import nargsort

_not_implemented_message = "{} does not implement {}."
Expand Down Expand Up @@ -484,10 +487,6 @@ def fillna(self, value=None, method=None, limit=None):
-------
filled : ExtensionArray with NA/NaN filled
"""
from pandas.api.types import is_array_like
from pandas.util._validators import validate_fillna_kwargs
from pandas.core.missing import pad_1d, backfill_1d

value, method = validate_fillna_kwargs(value, method)

mask = self.isna()
Expand Down Expand Up @@ -584,8 +583,6 @@ def unique(self):
-------
uniques : ExtensionArray
"""
from pandas import unique

uniques = unique(self.astype(object))
return self._from_sequence(uniques, dtype=self.dtype)

Expand Down Expand Up @@ -700,8 +697,6 @@ def factorize(self, na_sentinel: int = -1) -> Tuple[np.ndarray, ABCExtensionArra
# original ExtensionArray.
# 2. ExtensionArray.factorize.
# Complete control over factorization.
from pandas.core.algorithms import _factorize_array

arr, na_value = self._values_for_factorize()

labels, uniques = _factorize_array(
Expand Down Expand Up @@ -874,7 +869,7 @@ def copy(self) -> ABCExtensionArray:
def __repr__(self):
from pandas.io.formats.printing import format_object_summary

template = "{class_name}" "{data}\n" "Length: {length}, dtype: {dtype}"
template = "{class_name}{data}\nLength: {length}, dtype: {dtype}"
# the short repr has no trailing newline, while the truncated
# repr does. So we include a newline in our template, and strip
# any trailing newlines from format_object_summary
Expand Down
30 changes: 14 additions & 16 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,13 @@ def f(self, other):
if not self.ordered:
if op in ["__lt__", "__gt__", "__le__", "__ge__"]:
raise TypeError(
"Unordered Categoricals can only compare " "equality or not"
"Unordered Categoricals can only compare equality or not"
)
if isinstance(other, Categorical):
# Two Categoricals can only be be compared if the categories are
# the same (maybe up to ordering, depending on ordered)

msg = "Categoricals can only be compared if " "'categories' are the same."
msg = "Categoricals can only be compared if 'categories' are the same."
if len(self.categories) != len(other.categories):
raise TypeError(msg + " Categories are different lengths")
elif self.ordered and not (self.categories == other.categories).all():
Expand All @@ -109,7 +109,7 @@ def f(self, other):

if not (self.ordered == other.ordered):
raise TypeError(
"Categoricals can only be compared if " "'ordered' is the same"
"Categoricals can only be compared if 'ordered' is the same"
)
if not self.ordered and not self.categories.equals(other.categories):
# both unordered and different order
Expand Down Expand Up @@ -387,7 +387,7 @@ def __init__(

# FIXME
raise NotImplementedError(
"> 1 ndim Categorical are not " "supported at this time"
"> 1 ndim Categorical are not supported at this time"
)

# we're inferring from values
Expand Down Expand Up @@ -694,7 +694,7 @@ def from_codes(cls, codes, categories=None, ordered=None, dtype=None):
raise ValueError(msg)

if len(codes) and (codes.max() >= len(dtype.categories) or codes.min() < -1):
raise ValueError("codes need to be between -1 and " "len(categories)-1")
raise ValueError("codes need to be between -1 and len(categories)-1")

return cls(codes, dtype=dtype, fastpath=True)

Expand Down Expand Up @@ -1019,7 +1019,7 @@ def reorder_categories(self, new_categories, ordered=None, inplace=False):
inplace = validate_bool_kwarg(inplace, "inplace")
if set(self.dtype.categories) != set(new_categories):
raise ValueError(
"items in new_categories are not the same as in " "old categories"
"items in new_categories are not the same as in old categories"
)
return self.set_categories(new_categories, ordered=ordered, inplace=inplace)

Expand Down Expand Up @@ -1481,7 +1481,7 @@ def put(self, *args, **kwargs):
"""
Replace specific elements in the Categorical with given values.
"""
raise NotImplementedError(("'put' is not yet implemented " "for Categorical"))
raise NotImplementedError(("'put' is not yet implemented for Categorical"))

def dropna(self):
"""
Expand Down Expand Up @@ -1827,7 +1827,7 @@ def fillna(self, value=None, method=None, limit=None):
value = np.nan
if limit is not None:
raise NotImplementedError(
"specifying a limit for fillna has not " "been implemented yet"
"specifying a limit for fillna has not been implemented yet"
)

codes = self._codes
Expand Down Expand Up @@ -1963,7 +1963,7 @@ def take_nd(self, indexer, allow_fill=None, fill_value=None):
if fill_value in self.categories:
fill_value = self.categories.get_loc(fill_value)
else:
msg = "'fill_value' ('{}') is not in this Categorical's " "categories."
msg = "'fill_value' ('{}') is not in this Categorical's categories."
raise TypeError(msg.format(fill_value))

codes = take(self._codes, indexer, allow_fill=allow_fill, fill_value=fill_value)
Expand Down Expand Up @@ -2168,12 +2168,12 @@ def __setitem__(self, key, value):
# in a 2-d case be passd (slice(None),....)
if len(key) == 2:
if not com.is_null_slice(key[0]):
raise AssertionError("invalid slicing for a 1-ndim " "categorical")
raise AssertionError("invalid slicing for a 1-ndim categorical")
key = key[1]
elif len(key) == 1:
key = key[0]
else:
raise AssertionError("invalid slicing for a 1-ndim " "categorical")
raise AssertionError("invalid slicing for a 1-ndim categorical")

# slicing in Series or Categorical
elif isinstance(key, slice):
Expand Down Expand Up @@ -2561,9 +2561,7 @@ def __init__(self, data):
@staticmethod
def _validate(data):
if not is_categorical_dtype(data.dtype):
raise AttributeError(
"Can only use .cat accessor with a " "'category' dtype"
)
raise AttributeError("Can only use .cat accessor with a 'category' dtype")

def _delegate_property_get(self, name):
return getattr(self._parent, name)
Expand Down Expand Up @@ -2607,7 +2605,7 @@ def name(self):
# need to be updated. `name` will need to be removed from
# `ok_for_cat`.
warn(
"`Series.cat.name` has been deprecated. Use `Series.name` " "instead.",
"`Series.cat.name` has been deprecated. Use `Series.name` instead.",
FutureWarning,
stacklevel=2,
)
Expand All @@ -2619,7 +2617,7 @@ def index(self):
# need to be updated. `index` will need to be removed from
# ok_for_cat`.
warn(
"`Series.cat.index` has been deprecated. Use `Series.index` " "instead.",
"`Series.cat.index` has been deprecated. Use `Series.index` instead.",
FutureWarning,
stacklevel=2,
)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -1097,7 +1097,7 @@ def _sub_period_array(self, other):
)

if len(self) != len(other):
raise ValueError("cannot subtract arrays/indices of " "unequal length")
raise ValueError("cannot subtract arrays/indices of unequal length")
if self.freq != other.freq:
msg = DIFFERENT_FREQ.format(
cls=type(self).__name__, own_freq=self.freqstr, other_freq=other.freqstr
Expand Down
26 changes: 13 additions & 13 deletions pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ def _generate_range(

periods = dtl.validate_periods(periods)
if freq is None and any(x is None for x in [periods, start, end]):
raise ValueError("Must provide freq argument if no data is " "supplied")
raise ValueError("Must provide freq argument if no data is supplied")

if com.count_not_none(start, end, periods, freq) != 3:
raise ValueError(
Expand All @@ -496,7 +496,7 @@ def _generate_range(
if start is None and end is None:
if closed is not None:
raise ValueError(
"Closed has to be None if not both of start" "and end are defined"
"Closed has to be None if not both of startand end are defined"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

start and

)
if start is NaT or end is NaT:
raise ValueError("Neither `start` nor `end` can be NaT")
Expand Down Expand Up @@ -786,11 +786,11 @@ def _assert_tzawareness_compat(self, other):
elif self.tz is None:
if other_tz is not None:
raise TypeError(
"Cannot compare tz-naive and tz-aware " "datetime-like objects."
"Cannot compare tz-naive and tz-aware datetime-like objects."
)
elif other_tz is None:
raise TypeError(
"Cannot compare tz-naive and tz-aware " "datetime-like objects"
"Cannot compare tz-naive and tz-aware datetime-like objects"
)

# -----------------------------------------------------------------
Expand Down Expand Up @@ -833,7 +833,7 @@ def _add_offset(self, offset):

except NotImplementedError:
warnings.warn(
"Non-vectorized DateOffset being applied to Series " "or DatetimeIndex",
"Non-vectorized DateOffset being applied to Series or DatetimeIndex",
PerformanceWarning,
)
result = self.astype("O") + offset
Expand All @@ -851,7 +851,7 @@ def _sub_datetimelike_scalar(self, other):
if not self._has_same_tz(other):
# require tz compat
raise TypeError(
"Timestamp subtraction must have the same " "timezones or no timezones"
"Timestamp subtraction must have the same timezones or no timezones"
)

i8 = self.asi8
Expand Down Expand Up @@ -957,7 +957,7 @@ def tz_convert(self, tz):
if self.tz is None:
# tz naive, use tz_localize
raise TypeError(
"Cannot convert tz-naive timestamps, use " "tz_localize to localize"
"Cannot convert tz-naive timestamps, use tz_localize to localize"
)

# No conversion since timestamps are all UTC to begin with
Expand Down Expand Up @@ -1125,7 +1125,7 @@ def tz_localize(self, tz, ambiguous="raise", nonexistent="raise", errors=None):
nonexistent = "raise"
else:
raise ValueError(
"The errors argument must be either 'coerce' " "or 'raise'."
"The errors argument must be either 'coerce' or 'raise'."
)

nonexistent_options = ("raise", "NaT", "shift_forward", "shift_backward")
Expand Down Expand Up @@ -1274,7 +1274,7 @@ def to_period(self, freq=None):

if freq is None:
raise ValueError(
"You must pass a freq argument as " "current index has none."
"You must pass a freq argument as current index has none."
)

freq = get_period_alias(freq)
Expand Down Expand Up @@ -2047,7 +2047,7 @@ def maybe_convert_dtype(data, copy):
# Note: without explicitly raising here, PeriodIndex
# test_setops.test_join_does_not_recur fails
raise TypeError(
"Passing PeriodDtype data is invalid. " "Use `data.to_timestamp()` instead"
"Passing PeriodDtype data is invalid. Use `data.to_timestamp()` instead"
)

elif is_categorical_dtype(data):
Expand Down Expand Up @@ -2177,7 +2177,7 @@ def validate_tz_from_dtype(dtype, tz):
dtz = getattr(dtype, "tz", None)
if dtz is not None:
if tz is not None and not timezones.tz_compare(tz, dtz):
raise ValueError("cannot supply both a tz and a dtype" " with a tz")
raise ValueError("cannot supply both a tz and a dtype with a tz")
tz = dtz

if tz is not None and is_datetime64_dtype(dtype):
Expand Down Expand Up @@ -2216,15 +2216,15 @@ def _infer_tz_from_endpoints(start, end, tz):
inferred_tz = timezones.infer_tzinfo(start, end)
except Exception:
raise TypeError(
"Start and end cannot both be tz-aware with " "different timezones"
"Start and end cannot both be tz-aware with different timezones"
)

inferred_tz = timezones.maybe_get_tz(inferred_tz)
tz = timezones.maybe_get_tz(tz)

if tz is not None and inferred_tz is not None:
if not timezones.tz_compare(inferred_tz, tz):
raise AssertionError("Inferred time zone not equal to passed " "time zone")
raise AssertionError("Inferred time zone not equal to passed time zone")

elif inferred_tz is not None:
tz = inferred_tz
Expand Down
Loading