Skip to content
This repository was archived by the owner on Apr 10, 2024. It is now read-only.

Commit 76da01b

Browse files
committed
TST: test coverage, pep8
1 parent 71b65ab commit 76da01b

File tree

2 files changed

+54
-29
lines changed

2 files changed

+54
-29
lines changed

pandas/core/frame.py

+46-29
Original file line numberDiff line numberDiff line change
@@ -228,8 +228,8 @@ class DataFrame(NDFrame):
228228
_het_axis = 1
229229

230230
_AXIS_NUMBERS = {
231-
'index' : 0,
232-
'columns' : 1
231+
'index': 0,
232+
'columns': 1
233233
}
234234

235235
_AXIS_NAMES = dict((v, k) for k, v in _AXIS_NUMBERS.iteritems())
@@ -246,8 +246,8 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
246246
data : numpy ndarray (structured or homogeneous), dict, or DataFrame
247247
Dict can contain Series, arrays, constants, or list-like objects
248248
index : Index or array-like
249-
Index to use for resulting frame. Will default to np.arange(n) if no
250-
indexing information part of input data and no index provided
249+
Index to use for resulting frame. Will default to np.arange(n) if
250+
no indexing information part of input data and no index provided
251251
columns : Index or array-like
252252
Will default to np.arange(n) if not column labels provided
253253
dtype : dtype, default None
@@ -257,7 +257,7 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
257257
258258
Examples
259259
--------
260-
>>> d = {'col1' : ts1, 'col2' : ts2}
260+
>>> d = {'col1': ts1, 'col2': ts2}
261261
>>> df = DataFrame(data=d, index=index)
262262
>>> df2 = DataFrame(np.random.randn(10, 5))
263263
>>> df3 = DataFrame(np.random.randn(10, 5),
@@ -535,7 +535,8 @@ def __contains__(self, key):
535535
# Python 2 division methods
536536
if not py3compat.PY3:
537537
__div__ = _arith_method(operator.div, '__div__', default_axis=None)
538-
__rdiv__ = _arith_method(lambda x, y: y / x, '__rdiv__', default_axis=None)
538+
__rdiv__ = _arith_method(lambda x, y: y / x, '__rdiv__',
539+
default_axis=None)
539540

540541
def __neg__(self):
541542
arr = operator.neg(self.values)
@@ -855,7 +856,7 @@ def _helper_csvexcel(self, writer, na_rep=None, cols=None, header=True,
855856
index_label = []
856857
for i, name in enumerate(self.index.names):
857858
if name is None:
858-
name = '' # 'level_%d' % i
859+
name = ''
859860
index_label.append(name)
860861
else:
861862
index_label = self.index.name
@@ -892,7 +893,7 @@ def _helper_csvexcel(self, writer, na_rep=None, cols=None, header=True,
892893
if index:
893894
if nlevels == 1:
894895
row_fields = [idx]
895-
else: # handle MultiIndex
896+
else: # handle MultiIndex
896897
row_fields = list(idx)
897898
for i, col in enumerate(cols):
898899
val = series[col].get(idx)
@@ -960,8 +961,8 @@ def to_csv(self, path_or_buf, sep=",", na_rep='', cols=None,
960961
if close:
961962
f.close()
962963

963-
def to_excel(self, excel_writer, sheet_name = 'sheet1', na_rep='', cols=None, header=True,
964-
index=True, index_label=None):
964+
def to_excel(self, excel_writer, sheet_name='sheet1', na_rep='',
965+
cols=None, header=True, index=True, index_label=None):
965966
"""
966967
Write DataFrame to a excel sheet
967968
@@ -987,8 +988,8 @@ def to_excel(self, excel_writer, sheet_name = 'sheet1', na_rep='', cols=None, he
987988
Notes
988989
-----
989990
If passing an existing ExcelWriter object, then the sheet will be added
990-
to the existing workbook. This can be used to save different DataFrames
991-
to one workbook
991+
to the existing workbook. This can be used to save different
992+
DataFrames to one workbook
992993
>>> writer = ExcelWriter('output.xlsx')
993994
>>> df1.to_excel(writer,'sheet1')
994995
>>> df2.to_excel(writer,'sheet2')
@@ -1000,8 +1001,9 @@ def to_excel(self, excel_writer, sheet_name = 'sheet1', na_rep='', cols=None, he
10001001
excel_writer = ExcelWriter(excel_writer)
10011002
need_save = True
10021003
excel_writer.cur_sheet = sheet_name
1003-
self._helper_csvexcel(excel_writer, na_rep=na_rep, cols=cols, header=header,
1004-
index=index, index_label=index_label, encoding=None)
1004+
self._helper_csvexcel(excel_writer, na_rep=na_rep, cols=cols,
1005+
header=header, index=index,
1006+
index_label=index_label, encoding=None)
10051007
if need_save:
10061008
excel_writer.save()
10071009

@@ -1657,8 +1659,8 @@ def lookup(self, row_labels, col_labels):
16571659

16581660
def align(self, other, join='outer', axis=None, level=None, copy=True):
16591661
"""
1660-
Align two DataFrame object on their index and columns with the specified
1661-
join method for each axis Index
1662+
Align two DataFrame object on their index and columns with the
1663+
specified join method for each axis Index
16621664
16631665
Parameters
16641666
----------
@@ -2084,7 +2086,7 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None):
20842086
agg_obj = self
20852087
if subset is not None:
20862088
agg_axis_name = self._get_axis_name(agg_axis)
2087-
agg_obj = self.reindex(**{agg_axis_name : subset})
2089+
agg_obj = self.reindex(**{agg_axis_name: subset})
20882090

20892091
count = agg_obj.count(axis=agg_axis)
20902092

@@ -2102,7 +2104,7 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None):
21022104

21032105
labels = self._get_axis(axis)
21042106
new_labels = labels[mask]
2105-
return self.reindex(**{axis_name : new_labels})
2107+
return self.reindex(**{axis_name: new_labels})
21062108

21072109
def drop_duplicates(self, cols=None, take_last=False):
21082110
"""
@@ -2280,7 +2282,8 @@ def reorder_levels(self, order, axis=0):
22802282
-------
22812283
type of caller (new object)
22822284
"""
2283-
if not isinstance(self._get_axis(axis), MultiIndex): # pragma: no cover
2285+
if not isinstance(self._get_axis(axis),
2286+
MultiIndex): # pragma: no cover
22842287
raise Exception('Can only reorder levels on a hierarchical axis.')
22852288

22862289
result = self.copy()
@@ -2751,7 +2754,8 @@ def asfreq(self, freq, method=None):
27512754
if isinstance(freq, datetools.DateOffset):
27522755
dateRange = DateRange(self.index[0], self.index[-1], offset=freq)
27532756
else:
2754-
dateRange = DateRange(self.index[0], self.index[-1], time_rule=freq)
2757+
dateRange = DateRange(self.index[0], self.index[-1],
2758+
time_rule=freq)
27552759

27562760
return self.reindex(dateRange, method=method)
27572761

@@ -2864,8 +2868,8 @@ def apply(self, func, axis=0, broadcast=False, raw=False,
28642868
28652869
Notes
28662870
-----
2867-
Function passed should not have side effects. If the result is a Series,
2868-
it should have the same index
2871+
Function passed should not have side effects. If the result is a
2872+
Series, it should have the same index
28692873
28702874
Returns
28712875
-------
@@ -3038,7 +3042,8 @@ def append(self, other, ignore_index=False, verify_integrity=True):
30383042
if isinstance(other, dict):
30393043
other = Series(other)
30403044
if other.name is None and not ignore_index:
3041-
raise Exception('Can only append a Series if ignore_index=True')
3045+
raise Exception('Can only append a Series if '
3046+
'ignore_index=True')
30423047

30433048
index = None if other.name is None else [other.name]
30443049
other = other.reindex(self.columns, copy=False)
@@ -3114,7 +3119,7 @@ def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='',
31143119

31153120
if isinstance(other, Series):
31163121
assert(other.name is not None)
3117-
other = DataFrame({other.name : other})
3122+
other = DataFrame({other.name: other})
31183123

31193124
if isinstance(other, DataFrame):
31203125
return merge(self, other, left_on=on, how=how,
@@ -3343,7 +3348,8 @@ def _count_level(self, level, axis=0, numeric_only=False):
33433348
if axis == 1:
33443349
frame = frame.T
33453350

3346-
mask = notnull(frame.values).view(np.uint8) # python 2.5
3351+
# python 2.5
3352+
mask = notnull(frame.values).view(np.uint8)
33473353

33483354
level_index = frame.index.levels[level]
33493355
counts = lib.count_level_2d(mask, frame.index.labels[level],
@@ -3687,8 +3693,8 @@ def boxplot(self, column=None, by=None, ax=None, fontsize=None,
36873693
"""
36883694
import pandas.tools.plotting as plots
36893695
import matplotlib.pyplot as plt
3690-
ax = plots.boxplot(self, column=column, by=by, ax=ax, fontsize=fontsize,
3691-
grid=grid, rot=rot, **kwds)
3696+
ax = plots.boxplot(self, column=column, by=by, ax=ax,
3697+
fontsize=fontsize, grid=grid, rot=rot, **kwds)
36923698
plt.draw_if_interactive()
36933699
return ax
36943700

@@ -3791,7 +3797,7 @@ def _bar_plot(self, axes, subplots=False, use_index=True, grid=True,
37913797
bottom=np.zeros(N), linewidth=1, **kwds)
37923798
ax.set_title(col)
37933799
else:
3794-
rects.append(ax.bar(xinds + i * 0.5/K, y, 0.5/K,
3800+
rects.append(ax.bar(xinds + i * 0.5 / K, y, 0.5 / K,
37953801
bottom=np.zeros(N), label=col,
37963802
color=colors[i % len(colors)], **kwds))
37973803
labels.append(col)
@@ -3907,7 +3913,7 @@ def group_agg(values, bounds, f):
39073913
else:
39083914
right_bound = bounds[i + 1]
39093915

3910-
result[i] = f(values[left_bound : right_bound])
3916+
result[i] = f(values[left_bound:right_bound])
39113917

39123918
return result
39133919

@@ -4027,6 +4033,7 @@ def _rec_to_dict(arr):
40274033

40284034
return columns, sdict
40294035

4036+
40304037
def _list_to_sdict(data, columns):
40314038
if len(data) > 0 and isinstance(data[0], tuple):
40324039
content = list(lib.to_object_array_tuples(data).T)
@@ -4039,6 +4046,7 @@ def _list_to_sdict(data, columns):
40394046
return {}, columns
40404047
return _convert_object_array(content, columns)
40414048

4049+
40424050
def _list_of_dict_to_sdict(data, columns):
40434051
if columns is None:
40444052
gen = (x.keys() for x in data)
@@ -4047,6 +4055,7 @@ def _list_of_dict_to_sdict(data, columns):
40474055
content = list(lib.dicts_to_array(data, list(columns)).T)
40484056
return _convert_object_array(content, columns)
40494057

4058+
40504059
def _convert_object_array(content, columns):
40514060
if columns is None:
40524061
columns = range(len(content))
@@ -4059,6 +4068,7 @@ def _convert_object_array(content, columns):
40594068
for c, vals in zip(columns, content))
40604069
return sdict, columns
40614070

4071+
40624072
def _homogenize(data, index, columns, dtype=None):
40634073
from pandas.core.series import _sanitize_array
40644074

@@ -4104,9 +4114,11 @@ def _homogenize(data, index, columns, dtype=None):
41044114

41054115
return homogenized
41064116

4117+
41074118
def _put_str(s, space):
41084119
return ('%s' % s)[:space].ljust(space)
41094120

4121+
41104122
def _is_sequence(x):
41114123
try:
41124124
iter(x)
@@ -4115,6 +4127,7 @@ def _is_sequence(x):
41154127
except Exception:
41164128
return False
41174129

4130+
41184131
def install_ipython_completers(): # pragma: no cover
41194132
"""Register the DataFrame type with IPython's tab completion machinery, so
41204133
that it knows about accessing column names as attributes."""
@@ -4125,6 +4138,7 @@ def complete_dataframe(obj, prev_completions):
41254138
return prev_completions + [c for c in obj.columns \
41264139
if isinstance(c, basestring) and py3compat.isidentifier(c)]
41274140

4141+
41284142
# Importing IPython brings in about 200 modules, so we want to avoid it unless
41294143
# we're in IPython (when those modules are loaded anyway).
41304144
if "IPython" in sys.modules: # pragma: no cover
@@ -4133,6 +4147,7 @@ def complete_dataframe(obj, prev_completions):
41334147
except Exception:
41344148
pass
41354149

4150+
41364151
def _indexer_from_factorized(labels, shape, compress=True):
41374152
from pandas.core.groupby import get_group_index, _compress_group_index
41384153

@@ -4149,6 +4164,7 @@ def _indexer_from_factorized(labels, shape, compress=True):
41494164

41504165
return indexer
41514166

4167+
41524168
def _lexsort_indexer(keys):
41534169
labels = []
41544170
shape = []
@@ -4163,6 +4179,7 @@ def _lexsort_indexer(keys):
41634179
shape.append(len(rizer.uniques))
41644180
return _indexer_from_factorized(labels, shape)
41654181

4182+
41664183
if __name__ == '__main__':
41674184
import nose
41684185
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],

pandas/sparse/tests/test_sparse.py

+8
Original file line numberDiff line numberDiff line change
@@ -864,6 +864,9 @@ def _compare_to_dense(a, b, da, db, op):
864864
_compare_to_dense(s, frame, s,
865865
frame.to_dense(), op)
866866

867+
# it works!
868+
result = self.frame + self.frame.ix[:, ['A', 'B']]
869+
867870
def test_op_corners(self):
868871
empty = self.empty + self.empty
869872
self.assert_(not empty)
@@ -1126,6 +1129,11 @@ def _check_frame(frame):
11261129
reindexed['G'] = reindexed['A']
11271130
self.assert_('G' not in self.frame)
11281131

1132+
def test_take(self):
1133+
result = self.frame.take([1, 0, 2], axis=1)
1134+
expected = self.frame.reindex(columns=['B', 'A', 'C'])
1135+
assert_sp_frame_equal(result, expected)
1136+
11291137
def test_density(self):
11301138
df = SparseDataFrame({'A' : [nan, nan, nan, 0, 1, 2, 3, 4, 5, 6],
11311139
'B' : [0, 1, 2, nan, nan, nan, 3, 4, 5, 6],

0 commit comments

Comments
 (0)