Skip to content

Commit afbde4d

Browse files
committed
CLN: PEP8 cleanup of the io module
1 parent 4f9fefc commit afbde4d

24 files changed

+1020
-614
lines changed

pandas/computation/align.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,9 @@ def _align_core(terms):
152152
copy=False)
153153

154154
# need to fill if we have a bool dtype/array
155-
if isinstance(ti, (np.ndarray, pd.Series)) and ti.dtype == object and pd.lib.is_bool_array(ti.values):
155+
if (isinstance(ti, (np.ndarray, pd.Series))
156+
and ti.dtype == object
157+
and pd.lib.is_bool_array(ti.values)):
156158
r = f(fill_value=True)
157159
else:
158160
r = f()

pandas/computation/expr.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -512,18 +512,21 @@ def _possibly_evaluate_binop(self, op, op_class, lhs, rhs,
512512
res = op(lhs, rhs)
513513

514514
if self.engine != 'pytables':
515-
if (res.op in _cmp_ops_syms and getattr(lhs,'is_datetime',False) or getattr(rhs,'is_datetime',False)):
516-
# all date ops must be done in python bc numexpr doesn't work well
517-
# with NaT
515+
if (res.op in _cmp_ops_syms
516+
and getattr(lhs, 'is_datetime', False)
517+
or getattr(rhs, 'is_datetime', False)):
518+
# all date ops must be done in python bc numexpr doesn't work
519+
# well with NaT
518520
return self._possibly_eval(res, self.binary_ops)
519521

520522
if res.op in eval_in_python:
521523
# "in"/"not in" ops are always evaluated in python
522524
return self._possibly_eval(res, eval_in_python)
523525
elif self.engine != 'pytables':
524-
if (getattr(lhs,'return_type',None) == object or getattr(rhs,'return_type',None) == object):
525-
# evaluate "==" and "!=" in python if either of our operands has an
526-
# object return type
526+
if (getattr(lhs, 'return_type', None) == object
527+
or getattr(rhs, 'return_type', None) == object):
528+
# evaluate "==" and "!=" in python if either of our operands
529+
# has an object return type
527530
return self._possibly_eval(res, eval_in_python +
528531
maybe_eval_in_python)
529532
return res

pandas/computation/tests/test_eval.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1022,7 +1022,8 @@ def check_performance_warning_for_poor_alignment(self, engine, parser):
10221022

10231023
def test_performance_warning_for_poor_alignment(self):
10241024
for engine, parser in ENGINES_PARSERS:
1025-
yield self.check_performance_warning_for_poor_alignment, engine, parser
1025+
yield (self.check_performance_warning_for_poor_alignment, engine,
1026+
parser)
10261027

10271028

10281029
#------------------------------------

pandas/core/format.py

+21-19
Original file line numberDiff line numberDiff line change
@@ -264,8 +264,8 @@ class DataFrameFormatter(TableFormatter):
264264
def __init__(self, frame, buf=None, columns=None, col_space=None,
265265
header=True, index=True, na_rep='NaN', formatters=None,
266266
justify=None, float_format=None, sparsify=None,
267-
index_names=True, line_width=None, max_rows=None, max_cols=None,
268-
show_dimensions=False, **kwds):
267+
index_names=True, line_width=None, max_rows=None,
268+
max_cols=None, show_dimensions=False, **kwds):
269269
self.frame = frame
270270
self.buf = buf if buf is not None else StringIO()
271271
self.show_index_names = index_names
@@ -284,7 +284,8 @@ def __init__(self, frame, buf=None, columns=None, col_space=None,
284284
self.line_width = line_width
285285
self.max_rows = max_rows
286286
self.max_cols = max_cols
287-
self.max_rows_displayed = min(max_rows or len(self.frame),len(self.frame))
287+
self.max_rows_displayed = min(max_rows or len(self.frame),
288+
len(self.frame))
288289
self.show_dimensions = show_dimensions
289290

290291
if justify is None:
@@ -330,7 +331,8 @@ def _to_str_columns(self):
330331
*(_strlen(x) for x in cheader))
331332

332333
fmt_values = _make_fixed_width(fmt_values, self.justify,
333-
minimum=max_colwidth, truncated=truncate_v)
334+
minimum=max_colwidth,
335+
truncated=truncate_v)
334336

335337
max_len = max(np.max([_strlen(x) for x in fmt_values]),
336338
max_colwidth)
@@ -349,8 +351,8 @@ def _to_str_columns(self):
349351
if self.index:
350352
strcols.insert(0, str_index)
351353
if truncate_h:
352-
strcols.append(([''] * len(str_columns[-1])) \
353-
+ (['...'] * min(len(self.frame), self.max_rows)) )
354+
strcols.append(([''] * len(str_columns[-1]))
355+
+ (['...'] * min(len(self.frame), self.max_rows)))
354356

355357
return strcols
356358

@@ -382,8 +384,8 @@ def to_string(self, force_unicode=None):
382384
self.buf.writelines(text)
383385

384386
if self.show_dimensions:
385-
self.buf.write("\n\n[%d rows x %d columns]" \
386-
% (len(frame), len(frame.columns)) )
387+
self.buf.write("\n\n[%d rows x %d columns]"
388+
% (len(frame), len(frame.columns)))
387389

388390
def _join_multiline(self, *strcols):
389391
lwidth = self.line_width
@@ -484,10 +486,11 @@ def write(buf, frame, column_format, strcols):
484486

485487
def _format_col(self, i):
486488
formatter = self._get_formatter(i)
487-
return format_array((self.frame.iloc[:self.max_rows_displayed,i]).get_values(),
488-
formatter, float_format=self.float_format,
489-
na_rep=self.na_rep,
490-
space=self.col_space)
489+
return format_array(
490+
(self.frame.iloc[:self.max_rows_displayed, i]).get_values(),
491+
formatter, float_format=self.float_format, na_rep=self.na_rep,
492+
space=self.col_space
493+
)
491494

492495
def to_html(self, classes=None):
493496
"""
@@ -679,8 +682,6 @@ def write_result(self, buf):
679682
'not %s') % type(self.classes))
680683
_classes.extend(self.classes)
681684

682-
683-
684685
self.write('<table border="1" class="%s">' % ' '.join(_classes),
685686
indent)
686687

@@ -698,9 +699,9 @@ def write_result(self, buf):
698699

699700
self.write('</table>', indent)
700701
if self.fmt.show_dimensions:
701-
by = chr(215) if compat.PY3 else unichr(215) # ×
702+
by = chr(215) if compat.PY3 else unichr(215) # ×
702703
self.write(u('<p>%d rows %s %d columns</p>') %
703-
(len(frame), by, len(frame.columns)) )
704+
(len(frame), by, len(frame.columns)))
704705
_put_lines(buf, self.elements)
705706

706707
def _write_header(self, indent):
@@ -783,8 +784,9 @@ def _column_header():
783784
align=align)
784785

785786
if self.fmt.has_index_names:
786-
row = [x if x is not None else '' for x in self.frame.index.names] \
787-
+ [''] * min(len(self.columns), self.max_cols)
787+
row = [
788+
x if x is not None else '' for x in self.frame.index.names
789+
] + [''] * min(len(self.columns), self.max_cols)
788790
self.write_tr(row, indent, self.indent_delta, header=True)
789791

790792
indent -= self.indent_delta
@@ -851,7 +853,7 @@ def _write_hierarchical_rows(self, fmt_values, indent):
851853
truncate = (len(frame) > self.max_rows)
852854

853855
idx_values = frame.index[:nrows].format(sparsify=False, adjoin=False,
854-
names=False)
856+
names=False)
855857
idx_values = lzip(*idx_values)
856858

857859
if self.fmt.sparsify:

pandas/core/frame.py

+13-9
Original file line numberDiff line numberDiff line change
@@ -432,8 +432,9 @@ def _repr_fits_horizontal_(self, ignore_width=False):
432432
def _info_repr(self):
433433
"""True if the repr should show the info view."""
434434
info_repr_option = (get_option("display.large_repr") == "info")
435-
return info_repr_option and not \
436-
(self._repr_fits_horizontal_() and self._repr_fits_vertical_())
435+
return info_repr_option and not (
436+
self._repr_fits_horizontal_() and self._repr_fits_vertical_()
437+
)
437438

438439
def __unicode__(self):
439440
"""
@@ -486,8 +487,7 @@ def _repr_html_(self):
486487
return ('<div style="max-height:1000px;'
487488
'max-width:1500px;overflow:auto;">\n' +
488489
self.to_html(max_rows=max_rows, max_cols=max_cols,
489-
show_dimensions=True) \
490-
+ '\n</div>')
490+
show_dimensions=True) + '\n</div>')
491491
else:
492492
return None
493493

@@ -1283,7 +1283,8 @@ def to_string(self, buf=None, columns=None, col_space=None, colSpace=None,
12831283
index_names=index_names,
12841284
header=header, index=index,
12851285
line_width=line_width,
1286-
max_rows=max_rows, max_cols=max_cols,
1286+
max_rows=max_rows,
1287+
max_cols=max_cols,
12871288
show_dimensions=show_dimensions)
12881289
formatter.to_string()
12891290

@@ -1310,7 +1311,8 @@ def to_html(self, buf=None, columns=None, col_space=None, colSpace=None,
13101311
escape : boolean, default True
13111312
Convert the characters <, >, and & to HTML-safe sequences.=
13121313
max_rows : int, optional
1313-
Maximum number of rows to show before truncating. If None, show all.
1314+
Maximum number of rows to show before truncating. If None, show
1315+
all.
13141316
max_cols : int, optional
13151317
Maximum number of columns to show before truncating. If None, show
13161318
all.
@@ -1336,7 +1338,8 @@ def to_html(self, buf=None, columns=None, col_space=None, colSpace=None,
13361338
header=header, index=index,
13371339
bold_rows=bold_rows,
13381340
escape=escape,
1339-
max_rows=max_rows, max_cols=max_cols,
1341+
max_rows=max_rows,
1342+
max_cols=max_cols,
13401343
show_dimensions=show_dimensions)
13411344
formatter.to_html(classes=classes)
13421345

@@ -1904,7 +1907,8 @@ def _ensure_valid_index(self, value):
19041907

19051908
if not isinstance(value, Series):
19061909
raise ValueError('Cannot set a frame with no defined index '
1907-
'and a value that cannot be converted to a Series')
1910+
'and a value that cannot be converted to a '
1911+
'Series')
19081912
self._data.set_axis(1, value.index.copy(), check_axis=False)
19091913

19101914
def _set_item(self, key, value):
@@ -4597,7 +4601,7 @@ def extract_index(data):
45974601

45984602

45994603
def _prep_ndarray(values, copy=True):
4600-
if not isinstance(values, (np.ndarray,Series)):
4604+
if not isinstance(values, (np.ndarray, Series)):
46014605
if len(values) == 0:
46024606
return np.empty((0, 0), dtype=object)
46034607

pandas/core/generic.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ def is_dictlike(x):
4242

4343
def _single_replace(self, to_replace, method, inplace, limit):
4444
if self.ndim != 1:
45-
raise TypeError('cannot replace {0} with method {1} on a {2}'.format(to_replace,
46-
method,type(self).__name__))
45+
raise TypeError('cannot replace {0} with method {1} on a {2}'
46+
.format(to_replace, method, type(self).__name__))
4747

4848
orig_dtype = self.dtype
4949
result = self if inplace else self.copy()
@@ -2047,7 +2047,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
20472047
# passing a single value that is scalar like
20482048
# when value is None (GH5319), for compat
20492049
if not is_dictlike(to_replace) and not is_dictlike(regex):
2050-
to_replace = [ to_replace ]
2050+
to_replace = [to_replace]
20512051

20522052
if isinstance(to_replace, (tuple, list)):
20532053
return _single_replace(self, to_replace, method, inplace,

pandas/core/groupby.py

+11-6
Original file line numberDiff line numberDiff line change
@@ -649,9 +649,9 @@ def _index_with_as_index(self, b):
649649
original = self.obj.index
650650
gp = self.grouper
651651
levels = chain((gp.levels[i][gp.labels[i][b]]
652-
for i in range(len(gp.groupings))),
653-
(original.get_level_values(i)[b]
654-
for i in range(original.nlevels)))
652+
for i in range(len(gp.groupings))),
653+
(original.get_level_values(i)[b]
654+
for i in range(original.nlevels)))
655655
new = MultiIndex.from_arrays(list(levels))
656656
new.names = gp.names + original.names
657657
return new
@@ -2161,7 +2161,6 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
21612161
else:
21622162
key_index = Index(keys, name=key_names[0])
21632163

2164-
21652164
# make Nones an empty object
21662165
if com._count_not_none(*values) != len(values):
21672166
v = None
@@ -2170,14 +2169,20 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
21702169
break
21712170
if v is None:
21722171
return DataFrame()
2173-
values = [ x if x is not None else v._constructor(**v._construct_axes_dict()) for x in values ]
2172+
values = [
2173+
x if x is not None else
2174+
v._constructor(**v._construct_axes_dict())
2175+
for x in values
2176+
]
21742177

21752178
v = values[0]
21762179

21772180
if isinstance(v, (np.ndarray, Series)):
21782181
if isinstance(v, Series):
21792182
applied_index = self.obj._get_axis(self.axis)
2180-
all_indexed_same = _all_indexes_same([x.index for x in values ])
2183+
all_indexed_same = _all_indexes_same([
2184+
x.index for x in values
2185+
])
21812186
singular_series = (len(values) == 1 and
21822187
applied_index.nlevels == 1)
21832188

pandas/core/indexing.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -830,7 +830,9 @@ def _reindex(keys, level=None):
830830

831831
# see GH5553, make sure we use the right indexer
832832
new_indexer = np.arange(len(indexer))
833-
new_indexer[cur_indexer] = np.arange(len(result._get_axis(axis)))
833+
new_indexer[cur_indexer] = np.arange(
834+
len(result._get_axis(axis))
835+
)
834836
new_indexer[missing_indexer] = -1
835837

836838
# we have a non_unique selector, need to use the original

pandas/core/internals.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -3480,7 +3480,10 @@ def _delete_from_block(self, i, item):
34803480
super(SingleBlockManager, self)._delete_from_block(i, item)
34813481

34823482
# reset our state
3483-
self._block = self.blocks[0] if len(self.blocks) else make_block(np.array([],dtype=self._block.dtype),[],[])
3483+
self._block = (
3484+
self.blocks[0] if len(self.blocks) else
3485+
make_block(np.array([], dtype=self._block.dtype), [], [])
3486+
)
34843487
self._values = self._block.values
34853488

34863489
def get_slice(self, slobj, raise_on_error=False):

pandas/core/reshape.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -786,6 +786,7 @@ def lreshape(data, groups, dropna=True, label=None):
786786

787787
return DataFrame(mdata, columns=id_cols + pivot_cols)
788788

789+
789790
def wide_to_long(df, stubnames, i, j):
790791
"""
791792
Wide panel to long format. Less flexible but more user-friendly than melt.
@@ -848,8 +849,8 @@ def get_var_names(df, regex):
848849

849850
def melt_stub(df, stub, i, j):
850851
varnames = get_var_names(df, "^"+stub)
851-
newdf = melt(df, id_vars=i, value_vars=varnames,
852-
value_name=stub, var_name=j)
852+
newdf = melt(df, id_vars=i, value_vars=varnames, value_name=stub,
853+
var_name=j)
853854
newdf_j = newdf[j].str.replace(stub, "")
854855
try:
855856
newdf_j = newdf_j.astype(int)
@@ -870,6 +871,7 @@ def melt_stub(df, stub, i, j):
870871
newdf = newdf.merge(new, how="outer", on=id_vars + [j], copy=False)
871872
return newdf.set_index([i, j])
872873

874+
873875
def convert_dummies(data, cat_variables, prefix_sep='_'):
874876
"""
875877
Compute DataFrame with specified columns converted to dummy variables (0 /

pandas/io/auth.py

+1
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ def init_service(http):
117117
"""
118118
return gapi.build('analytics', 'v3', http=http)
119119

120+
120121
def reset_default_token_store():
121122
import os
122123
os.remove(DEFAULT_TOKEN_FILE)

pandas/io/clipboard.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from pandas import compat, get_option, DataFrame
33
from pandas.compat import StringIO
44

5+
56
def read_clipboard(**kwargs): # pragma: no cover
67
"""
78
Read text from clipboard and pass to read_table. See read_table for the
@@ -20,7 +21,10 @@ def read_clipboard(**kwargs): # pragma: no cover
2021
# try to decode (if needed on PY3)
2122
if compat.PY3:
2223
try:
23-
text = compat.bytes_to_str(text,encoding=kwargs.get('encoding') or get_option('display.encoding'))
24+
text = compat.bytes_to_str(
25+
text, encoding=(kwargs.get('encoding') or
26+
get_option('display.encoding'))
27+
)
2428
except:
2529
pass
2630
return read_table(StringIO(text), **kwargs)
@@ -58,7 +62,7 @@ def to_clipboard(obj, excel=None, sep=None, **kwargs): # pragma: no cover
5862
if sep is None:
5963
sep = '\t'
6064
buf = StringIO()
61-
obj.to_csv(buf,sep=sep, **kwargs)
65+
obj.to_csv(buf, sep=sep, **kwargs)
6266
clipboard_set(buf.getvalue())
6367
return
6468
except:
@@ -70,4 +74,3 @@ def to_clipboard(obj, excel=None, sep=None, **kwargs): # pragma: no cover
7074
else:
7175
objstr = str(obj)
7276
clipboard_set(objstr)
73-

0 commit comments

Comments
 (0)