Skip to content

Commit

Permalink
CLN: PEP8 cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
alefnula committed Nov 16, 2013
1 parent 4718ffe commit a4a71f8
Show file tree
Hide file tree
Showing 33 changed files with 1,743 additions and 1,185 deletions.
123 changes: 63 additions & 60 deletions pandas/compat/__init__.py

Large diffs are not rendered by default.

16 changes: 12 additions & 4 deletions pandas/compat/pickle_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from pandas.core.series import Series, TimeSeries
from pandas.sparse.series import SparseSeries, SparseTimeSeries


def load_reduce(self):
stack = self.stack
args = stack.pop()
Expand All @@ -18,7 +19,8 @@ def load_reduce(self):
if n == u('DeprecatedSeries') or n == u('DeprecatedTimeSeries'):
stack[-1] = object.__new__(Series)
return
elif n == u('DeprecatedSparseSeries') or n == u('DeprecatedSparseTimeSeries'):
elif (n == u('DeprecatedSparseSeries') or
n == u('DeprecatedSparseTimeSeries')):
stack[-1] = object.__new__(SparseSeries)
return

Expand All @@ -28,7 +30,9 @@ def load_reduce(self):

# try to reencode the arguments
if self.encoding is not None:
args = tuple([ arg.encode(self.encoding) if isinstance(arg, string_types) else arg for arg in args ])
args = tuple([arg.encode(self.encoding)
if isinstance(arg, string_types)
else arg for arg in args])
try:
stack[-1] = func(*args)
return
Expand All @@ -51,9 +55,9 @@ class Unpickler(pkl.Unpickler):

Unpickler.dispatch[pkl.REDUCE[0]] = load_reduce


def load(fh, encoding=None, compat=False, is_verbose=False):
"""
load a pickle, with a provided encoding
"""load a pickle, with a provided encoding
if compat is True:
fake the old class hierarchy
Expand Down Expand Up @@ -90,14 +94,18 @@ def load(fh, encoding=None, compat=False, is_verbose=False):
pandas.sparse.series.SparseSeries = SparseSeries
pandas.sparse.series.SparseTimeSeries = SparseTimeSeries


class DeprecatedSeries(np.ndarray, Series):
pass


class DeprecatedTimeSeries(DeprecatedSeries):
pass


class DeprecatedSparseSeries(DeprecatedSeries):
pass


class DeprecatedSparseTimeSeries(DeprecatedSparseSeries):
pass
10 changes: 4 additions & 6 deletions pandas/compat/scipy.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@


def scoreatpercentile(a, per, limit=(), interpolation_method='fraction'):
"""
Calculate the score at the given `per` percentile of the sequence `a`.
"""Calculate the score at the given `per` percentile of the sequence `a`.
For example, the score at `per=50` is the median. If the desired quantile
lies between two data points, we interpolate between them, according to
Expand Down Expand Up @@ -65,7 +64,7 @@ def scoreatpercentile(a, per, limit=(), interpolation_method='fraction'):
values = values[(limit[0] <= values) & (values <= limit[1])]

idx = per / 100. * (values.shape[0] - 1)
if (idx % 1 == 0):
if idx % 1 == 0:
score = values[idx]
else:
if interpolation_method == 'fraction':
Expand Down Expand Up @@ -153,8 +152,7 @@ def fastsort(a):


def percentileofscore(a, score, kind='rank'):
'''
The percentile rank of a score relative to a list of scores.
"""The percentile rank of a score relative to a list of scores.
A `percentileofscore` of, for example, 80% means that 80% of the
scores in `a` are below the given score. In the case of gaps or
Expand Down Expand Up @@ -217,7 +215,7 @@ def percentileofscore(a, score, kind='rank'):
>>> percentileofscore([1, 2, 3, 3, 4], 3, kind='mean')
60.0
'''
"""
a = np.array(a)
n = len(a)

Expand Down
14 changes: 7 additions & 7 deletions pandas/computation/align.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ def wrapper(terms):

@_filter_special_cases
def _align_core(terms):
term_index = [i for i, term in enumerate(terms) if hasattr(term.value,
'axes')]
term_index = [i for i, term in enumerate(terms)
if hasattr(term.value, 'axes')]
term_dims = [terms[i].value.ndim for i in term_index]
ndims = pd.Series(dict(zip(term_index, term_dims)))

Expand Down Expand Up @@ -139,10 +139,10 @@ def _align_core(terms):

ordm = np.log10(abs(reindexer_size - term_axis_size))
if ordm >= 1 and reindexer_size >= 10000:
warnings.warn("Alignment difference on axis {0} is larger"
" than an order of magnitude on term {1!r}, "
"by more than {2:.4g}; performance may suffer"
"".format(axis, terms[i].name, ordm),
warnings.warn('Alignment difference on axis {0} is larger '
'than an order of magnitude on term {1!r}, '
'by more than {2:.4g}; performance may '
'suffer'.format(axis, terms[i].name, ordm),
category=pd.io.common.PerformanceWarning)

if transpose:
Expand Down Expand Up @@ -237,7 +237,7 @@ def _reconstruct_object(typ, obj, axes, dtype):
res_t = dtype

if (not isinstance(typ, partial) and
issubclass(typ, pd.core.generic.PandasObject)):
issubclass(typ, pd.core.generic.PandasObject)):
return typ(obj, dtype=res_t, **axes)

# special case for pathological things like ~True/~False
Expand Down
36 changes: 19 additions & 17 deletions pandas/computation/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ class Scope(StringMixin):
__slots__ = ('globals', 'locals', 'resolvers', '_global_resolvers',
'resolver_keys', '_resolver', 'level', 'ntemps', 'target')

def __init__(self, gbls=None, lcls=None, level=1, resolvers=None, target=None):
def __init__(self, gbls=None, lcls=None, level=1, resolvers=None,
target=None):
self.level = level
self.resolvers = tuple(resolvers or [])
self.globals = dict()
Expand Down Expand Up @@ -133,11 +134,12 @@ def __init__(self, gbls=None, lcls=None, level=1, resolvers=None, target=None):
self.resolver_dict.update(dict(o))

def __unicode__(self):
return com.pprint_thing("locals: {0}\nglobals: {0}\nresolvers: "
"{0}\ntarget: {0}".format(list(self.locals.keys()),
list(self.globals.keys()),
list(self.resolver_keys),
self.target))
return com.pprint_thing(
'locals: {0}\nglobals: {0}\nresolvers: '
'{0}\ntarget: {0}'.format(list(self.locals.keys()),
list(self.globals.keys()),
list(self.resolver_keys),
self.target))

def __getitem__(self, key):
return self.resolve(key, globally=False)
Expand Down Expand Up @@ -499,9 +501,8 @@ def _possibly_evaluate_binop(self, op, op_class, lhs, rhs,
maybe_eval_in_python=('==', '!=')):
res = op(lhs, rhs)

if (res.op in _cmp_ops_syms and
lhs.is_datetime or rhs.is_datetime and
self.engine != 'pytables'):
if (res.op in _cmp_ops_syms and lhs.is_datetime or rhs.is_datetime and
self.engine != 'pytables'):
# all date ops must be done in python bc numexpr doesn't work well
# with NaT
return self._possibly_eval(res, self.binary_ops)
Expand Down Expand Up @@ -594,18 +595,20 @@ def visit_Assign(self, node, **kwargs):
if len(node.targets) != 1:
raise SyntaxError('can only assign a single expression')
if not isinstance(node.targets[0], ast.Name):
raise SyntaxError('left hand side of an assignment must be a single name')
raise SyntaxError('left hand side of an assignment must be a '
'single name')
if self.env.target is None:
raise ValueError('cannot assign without a target object')

try:
assigner = self.visit(node.targets[0], **kwargs)
except (UndefinedVariableError):
except UndefinedVariableError:
assigner = node.targets[0].id

self.assigner = getattr(assigner,'name',assigner)
self.assigner = getattr(assigner, 'name', assigner)
if self.assigner is None:
raise SyntaxError('left hand side of an assignment must be a single resolvable name')
raise SyntaxError('left hand side of an assignment must be a '
'single resolvable name')

return self.visit(node.value, **kwargs)

Expand All @@ -622,7 +625,7 @@ def visit_Attribute(self, node, **kwargs):
name = self.env.add_tmp(v)
return self.term_type(name, self.env)
except AttributeError:
# something like datetime.datetime where scope is overriden
# something like datetime.datetime where scope is overridden
if isinstance(value, ast.Name) and value.id == attr:
return resolved

Expand Down Expand Up @@ -699,8 +702,7 @@ def visitor(x, y):
return reduce(visitor, operands)


_python_not_supported = frozenset(['Dict', 'Call', 'BoolOp',
'In', 'NotIn'])
_python_not_supported = frozenset(['Dict', 'Call', 'BoolOp', 'In', 'NotIn'])
_numexpr_supported_calls = frozenset(_reductions + _mathops)


Expand Down Expand Up @@ -744,7 +746,7 @@ def __init__(self, expr, engine='numexpr', parser='pandas', env=None,

@property
def assigner(self):
return getattr(self._visitor,'assigner',None)
return getattr(self._visitor, 'assigner', None)

def __call__(self):
self.env.locals['truediv'] = self.truediv
Expand Down
17 changes: 9 additions & 8 deletions pandas/computation/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Expressions
-----------
Offer fast expression evaluation thru numexpr
Offer fast expression evaluation through numexpr
"""

Expand All @@ -22,9 +22,10 @@
_where = None

# the set of dtypes that we will allow pass to numexpr
_ALLOWED_DTYPES = dict(
evaluate=set(['int64', 'int32', 'float64', 'float32', 'bool']),
where=set(['int64', 'float64', 'bool']))
_ALLOWED_DTYPES = {
'evaluate': set(['int64', 'int32', 'float64', 'float32', 'bool']),
'where': set(['int64', 'float64', 'bool'])
}

# the minimum prod shape that we will use numexpr
_MIN_ELEMENTS = 10000
Expand Down Expand Up @@ -100,10 +101,10 @@ def _evaluate_numexpr(op, op_str, a, b, raise_on_error=False, truediv=True,
'b_value': b_value},
casting='safe', truediv=truediv,
**eval_kwargs)
except (ValueError) as detail:
except ValueError as detail:
if 'unknown type object' in str(detail):
pass
except (Exception) as detail:
except Exception as detail:
if raise_on_error:
raise

Expand Down Expand Up @@ -135,10 +136,10 @@ def _where_numexpr(cond, a, b, raise_on_error=False):
'a_value': a_value,
'b_value': b_value},
casting='safe')
except (ValueError) as detail:
except ValueError as detail:
if 'unknown type object' in str(detail):
pass
except (Exception) as detail:
except Exception as detail:
if raise_on_error:
raise TypeError(str(detail))

Expand Down
1 change: 0 additions & 1 deletion pandas/computation/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,6 @@ def name(self):
return self.value



_bool_op_map = {'not': '~', 'and': '&', 'or': '|'}


Expand Down
Loading

0 comments on commit a4a71f8

Please sign in to comment.