Skip to content

STY: avoid backslash #23073

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
Oct 12, 2018
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
4 changes: 2 additions & 2 deletions pandas/compat/numpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ def np_array_datetime64_compat(arr, *args, **kwargs):
if not _np_version_under1p11:

# is_list_like
if hasattr(arr, '__iter__') and not \
isinstance(arr, string_and_binary_types):
if (hasattr(arr, '__iter__') and
not isinstance(arr, string_and_binary_types)):
arr = [tz_replacer(s) for s in arr]
else:
arr = tz_replacer(arr)
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,8 +275,8 @@ def match(to_match, values, na_sentinel=-1):
# replace but return a numpy array
# use a Series because it handles dtype conversions properly
from pandas import Series
result = Series(result.ravel()).replace(-1, na_sentinel).values.\
reshape(result.shape)
result = Series(result.ravel()).replace(-1, na_sentinel)
result = result.values.reshape(result.shape)

return result

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,8 +395,8 @@ def nested_renaming_depr(level=4):

elif isinstance(obj, ABCSeries):
nested_renaming_depr()
elif isinstance(obj, ABCDataFrame) and \
k not in obj.columns:
elif (isinstance(obj, ABCDataFrame) and
k not in obj.columns):
raise KeyError(
"Column '{col}' does not exist!".format(col=k))

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -5651,8 +5651,8 @@ def fillna(self, value=None, method=None, axis=None, inplace=False,
# fill in 2d chunks
result = {col: s.fillna(method=method, value=value)
for col, s in self.iteritems()}
new_obj = self._constructor.\
from_dict(result).__finalize__(self)
prelim_obj = self._constructor.from_dict(result)
new_obj = prelim_obj.__finalize__(self)
new_data = new_obj._data

else:
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1027,8 +1027,9 @@ def nunique(self, dropna=True):
try:
sorter = np.lexsort((val, ids))
except TypeError: # catches object dtypes
assert val.dtype == object, \
'val.dtype must be object, got %s' % val.dtype
msg = ('val.dtype must be object, got {dtype}'
.format(dtype=val.dtype))
assert val.dtype == object, msg
val, _ = algorithms.factorize(val, sort=False)
sorter = np.lexsort((val, ids))
_isna = lambda a: a == -1
Expand Down
14 changes: 8 additions & 6 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,8 +578,8 @@ def wrapper(*args, **kwargs):
# a little trickery for aggregation functions that need an axis
# argument
kwargs_with_axis = kwargs.copy()
if 'axis' not in kwargs_with_axis or \
kwargs_with_axis['axis'] is None:
if ('axis' not in kwargs_with_axis or
kwargs_with_axis['axis'] is None):
kwargs_with_axis['axis'] = self.axis

def curried_with_axis(x):
Expand Down Expand Up @@ -1490,8 +1490,10 @@ def nth(self, n, dropna=None):
self._set_group_selection()

if not dropna:
mask = np.in1d(self._cumcount_array(), nth_values) | \
np.in1d(self._cumcount_array(ascending=False) + 1, -nth_values)
mask_left = np.in1d(self._cumcount_array(), nth_values)
mask_right = np.in1d(self._cumcount_array(ascending=False) + 1,
-nth_values)
mask = mask_left | mask_right

out = self._selected_obj[mask]
if not self.as_index:
Expand Down Expand Up @@ -1552,8 +1554,8 @@ def nth(self, n, dropna=None):
result.loc[mask] = np.nan

# reset/reindex to the original groups
if len(self.obj) == len(dropped) or \
len(result) == len(self.grouper.result_index):
if (len(self.obj) == len(dropped) or
len(result) == len(self.grouper.result_index)):
result.index = self.grouper.result_index
else:
result = result.reindex(self.grouper.result_index)
Expand Down
28 changes: 14 additions & 14 deletions pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,8 @@ def _set_grouper(self, obj, sort=False):
if self.key is not None:
key = self.key
# The 'on' is already defined
if getattr(self.grouper, 'name', None) == key and \
isinstance(obj, ABCSeries):
if (getattr(self.grouper, 'name', None) == key and
isinstance(obj, ABCSeries)):
ax = self._grouper.take(obj.index)
else:
if key not in obj._info_axis:
Expand Down Expand Up @@ -530,9 +530,9 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True,
except Exception:
all_in_columns_index = False

if not any_callable and not all_in_columns_index and \
not any_arraylike and not any_groupers and \
match_axis_length and level is None:
if (not any_callable and not all_in_columns_index and
not any_arraylike and not any_groupers and
match_axis_length and level is None):
keys = [com.asarray_tuplesafe(keys)]

if isinstance(level, (tuple, list)):
Expand Down Expand Up @@ -593,15 +593,15 @@ def is_in_obj(gpr):

# create the Grouping
# allow us to passing the actual Grouping as the gpr
ping = Grouping(group_axis,
gpr,
obj=obj,
name=name,
level=level,
sort=sort,
observed=observed,
in_axis=in_axis) \
if not isinstance(gpr, Grouping) else gpr
ping = (Grouping(group_axis,
gpr,
obj=obj,
name=name,
level=level,
sort=sort,
observed=observed,
in_axis=in_axis)
if not isinstance(gpr, Grouping) else gpr)

groupings.append(ping)

Expand Down
9 changes: 5 additions & 4 deletions pandas/core/groupby/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,8 +521,8 @@ def _cython_operation(self, kind, values, how, axis, min_count=-1,
result = result.astype('float64')
result[mask] = np.nan

if kind == 'aggregate' and \
self._filter_empty_groups and not counts.all():
if (kind == 'aggregate' and
self._filter_empty_groups and not counts.all()):
if result.ndim == 2:
try:
result = lib.row_bool_subset(
Expand Down Expand Up @@ -743,8 +743,9 @@ def group_info(self):
else:
comp_ids = np.repeat(np.r_[-1, np.arange(ngroups)], rep)

return comp_ids.astype('int64', copy=False), \
obs_group_ids.astype('int64', copy=False), ngroups
return (comp_ids.astype('int64', copy=False),
obs_group_ids.astype('int64', copy=False),
ngroups)

@cache_readonly
def ngroups(self):
Expand Down
8 changes: 4 additions & 4 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1836,8 +1836,8 @@ def _get_partial_string_timestamp_match_key(self, key, labels):
"""Translate any partial string timestamp matches in key, returning the
new key (GH 10331)"""
if isinstance(labels, MultiIndex):
if isinstance(key, compat.string_types) and \
labels.levels[0].is_all_dates:
if (isinstance(key, compat.string_types) and
labels.levels[0].is_all_dates):
# Convert key '2016-01-01' to
# ('2016-01-01'[, slice(None, None, None)]+)
key = tuple([key] + [slice(None)] * (len(labels.levels) - 1))
Expand All @@ -1847,8 +1847,8 @@ def _get_partial_string_timestamp_match_key(self, key, labels):
# (..., slice('2016-01-01', '2016-01-01', None), ...)
new_key = []
for i, component in enumerate(key):
if isinstance(component, compat.string_types) and \
labels.levels[i].is_all_dates:
if (isinstance(component, compat.string_types) and
labels.levels[i].is_all_dates):
new_key.append(slice(component, component, None))
else:
new_key.append(component)
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/internals/concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,8 @@ def get_reindexed_values(self, empty_dtype, upcasted_na):
if len(values) and values[0] is None:
fill_value = None

if getattr(self.block, 'is_datetimetz', False) or \
is_datetimetz(empty_dtype):
if (getattr(self.block, 'is_datetimetz', False) or
is_datetimetz(empty_dtype)):
if self.block is None:
array = empty_dtype.construct_array_type()
missing_arr = array([fill_value], dtype=empty_dtype)
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,8 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
margins_name=margins_name, fill_value=fill_value)

# discard the top level
if values_passed and not values_multi and not table.empty and \
(table.columns.nlevels > 1):
if (values_passed and not values_multi and not table.empty and
(table.columns.nlevels > 1)):
table = table[values[0]]

if len(index) == 0 and len(columns) > 0:
Expand Down
5 changes: 2 additions & 3 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -745,9 +745,8 @@ def check_len(item, name):

if is_list_like(item):
if not len(item) == data_to_encode.shape[1]:
len_msg = \
len_msg.format(name=name, len_item=len(item),
len_enc=data_to_encode.shape[1])
len_msg = len_msg.format(name=name, len_item=len(item),
len_enc=data_to_encode.shape[1])
raise ValueError(len_msg)

check_len(prefix, 'prefix')
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/tools/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,8 +724,9 @@ def calc_with_mask(carg, mask):
result = np.empty(carg.shape, dtype='M8[ns]')
iresult = result.view('i8')
iresult[~mask] = tslibs.iNaT
result[mask] = calc(carg[mask].astype(np.float64).astype(np.int64)). \
astype('M8[ns]')

masked_result = calc(carg[mask].astype(np.float64).astype(np.int64))
result[mask] = masked_result.astype('M8[ns]')
return result

# try intlike / strings that are ints
Expand Down
8 changes: 4 additions & 4 deletions pandas/core/window.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,11 @@ def is_freq_type(self):
def validate(self):
if self.center is not None and not is_bool(self.center):
raise ValueError("center must be a boolean")
if self.min_periods is not None and not \
is_integer(self.min_periods):
if (self.min_periods is not None and
not is_integer(self.min_periods)):
raise ValueError("min_periods must be an integer")
if self.closed is not None and self.closed not in \
['right', 'both', 'left', 'neither']:
if (self.closed is not None and
self.closed not in ['right', 'both', 'left', 'neither']):
raise ValueError("closed must be 'right', 'left', 'both' or "
"'neither'")

Expand Down
4 changes: 2 additions & 2 deletions pandas/io/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,8 +430,8 @@ def _get_handle(path_or_buf, mode, encoding=None, compression=None,
handles.append(f)

# in Python 3, convert BytesIO or fileobjects passed with an encoding
if compat.PY3 and is_text and\
(compression or isinstance(f, need_text_wrapping)):
if (compat.PY3 and is_text and
(compression or isinstance(f, need_text_wrapping))):
from io import TextIOWrapper
f = TextIOWrapper(f, encoding=encoding)
handles.append(f)
Expand Down
8 changes: 4 additions & 4 deletions pandas/io/excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -1755,14 +1755,14 @@ def convert(cls, style_dict, num_format_str=None):
props[k] = ['none', 'thin', 'medium', 'dashed', 'dotted',
'thick', 'double', 'hair', 'mediumDashed',
'dashDot', 'mediumDashDot', 'dashDotDot',
'mediumDashDotDot', 'slantDashDot'].\
index(props[k])
'mediumDashDotDot',
'slantDashDot'].index(props[k])
except ValueError:
props[k] = 2

if isinstance(props.get('font_script'), string_types):
props['font_script'] = ['baseline', 'superscript', 'subscript'].\
index(props['font_script'])
props['font_script'] = ['baseline', 'superscript',
'subscript'].index(props['font_script'])

if isinstance(props.get('underline'), string_types):
props['underline'] = {'none': 0, 'single': 1, 'double': 2,
Expand Down
7 changes: 3 additions & 4 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@
PackageLoader, Environment, ChoiceLoader, FileSystemLoader
)
except ImportError:
msg = "pandas.Styler requires jinja2. "\
"Please install with `conda install Jinja2`\n"\
"or `pip install Jinja2`"
raise ImportError(msg)
raise ImportError("pandas.Styler requires jinja2. "
"Please install with `conda install Jinja2`\n"
"or `pip install Jinja2`")

from pandas.core.dtypes.common import is_float, is_string_like

Expand Down
5 changes: 2 additions & 3 deletions pandas/io/formats/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,8 @@ def get_terminal_size():
if tuple_xy is None:
tuple_xy = _get_terminal_size_tput()
# needed for window's python in cygwin's xterm!
if current_os == 'Linux' or \
current_os == 'Darwin' or \
current_os.startswith('CYGWIN'):
if (current_os == 'Linux' or current_os == 'Darwin' or
current_os.startswith('CYGWIN')):
tuple_xy = _get_terminal_size_linux()
if tuple_xy is None:
tuple_xy = (80, 25) # default value
Expand Down
9 changes: 4 additions & 5 deletions pandas/io/json/normalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,11 +250,10 @@ def _recursive_extract(data, path, seen_meta, level=0):
if errors == 'ignore':
meta_val = np.nan
else:
raise \
KeyError("Try running with "
"errors='ignore' as key "
"{err} is not always present"
.format(err=e))
raise KeyError("Try running with "
"errors='ignore' as key "
"{err} is not always present"
.format(err=e))
meta_vals[key].append(meta_val)

records.extend(recs)
Expand Down
28 changes: 14 additions & 14 deletions pandas/io/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -883,26 +883,26 @@ def _clean_options(self, options, engine):
# C engine not supported yet
if engine == 'c':
if options['skipfooter'] > 0:
fallback_reason = "the 'c' engine does not support"\
" skipfooter"
fallback_reason = ("the 'c' engine does not support"
" skipfooter")
engine = 'python'

encoding = sys.getfilesystemencoding() or 'utf-8'
if sep is None and not delim_whitespace:
if engine == 'c':
fallback_reason = "the 'c' engine does not support"\
" sep=None with delim_whitespace=False"
fallback_reason = ("the 'c' engine does not support"
" sep=None with delim_whitespace=False")
engine = 'python'
elif sep is not None and len(sep) > 1:
if engine == 'c' and sep == r'\s+':
result['delim_whitespace'] = True
del result['delimiter']
elif engine not in ('python', 'python-fwf'):
# wait until regex engine integrated
fallback_reason = "the 'c' engine does not support"\
" regex separators (separators > 1 char and"\
r" different from '\s+' are"\
" interpreted as regex)"
fallback_reason = ("the 'c' engine does not support"
" regex separators (separators > 1 char and"
r" different from '\s+' are"
" interpreted as regex)")
engine = 'python'
elif delim_whitespace:
if 'python' in engine:
Expand All @@ -915,10 +915,10 @@ def _clean_options(self, options, engine):
except UnicodeDecodeError:
encodeable = False
if not encodeable and engine not in ('python', 'python-fwf'):
fallback_reason = "the separator encoded in {encoding}" \
" is > 1 char long, and the 'c' engine" \
" does not support such separators".format(
encoding=encoding)
fallback_reason = ("the separator encoded in {encoding}"
" is > 1 char long, and the 'c' engine"
" does not support such separators"
.format(encoding=encoding))
engine = 'python'

quotechar = options['quotechar']
Expand Down Expand Up @@ -3203,8 +3203,8 @@ def _clean_index_names(columns, index_col):
index_names.append(name)

# hack
if isinstance(index_names[0], compat.string_types)\
and 'Unnamed' in index_names[0]:
if (isinstance(index_names[0], compat.string_types) and
'Unnamed' in index_names[0]):
index_names[0] = None

return index_names, columns, index_col
Expand Down
4 changes: 2 additions & 2 deletions pandas/io/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -1804,8 +1804,8 @@ def validate_metadata(self, handler):
if self.meta == 'category':
new_metadata = self.metadata
cur_metadata = handler.read_metadata(self.cname)
if new_metadata is not None and cur_metadata is not None \
and not array_equivalent(new_metadata, cur_metadata):
if (new_metadata is not None and cur_metadata is not None and
not array_equivalent(new_metadata, cur_metadata)):
raise ValueError("cannot append a categorical with "
"different categories to the existing")

Expand Down
Loading