Skip to content

Commit 206f859

Browse files
committed
DEPR: deprecate .as_blocks()
closes #17302
1 parent 965c1c8 commit 206f859

File tree

11 files changed

+77
-47
lines changed

11 files changed

+77
-47
lines changed

doc/source/10min.rst

+1-11
Original file line numberDiff line numberDiff line change
@@ -95,17 +95,7 @@ will be completed:
9595
df2.append df2.combine_first
9696
df2.apply df2.compound
9797
df2.applymap df2.consolidate
98-
df2.as_blocks df2.convert_objects
99-
df2.asfreq df2.copy
100-
df2.as_matrix df2.corr
101-
df2.astype df2.corrwith
102-
df2.at df2.count
103-
df2.at_time df2.cov
104-
df2.axes df2.cummax
105-
df2.B df2.cummin
106-
df2.between_time df2.cumprod
107-
df2.bfill df2.cumsum
108-
df2.blocks df2.D
98+
df2.D
10999

110100
As you can see, the columns ``A``, ``B``, ``C``, and ``D`` are automatically
111101
tab completed. ``E`` is there as well; the rest of the attributes have been

doc/source/whatsnew/v0.21.0.txt

+1-2
Original file line numberDiff line numberDiff line change
@@ -488,10 +488,9 @@ Other API Changes
488488
Deprecations
489489
~~~~~~~~~~~~
490490
- :func:`read_excel()` has deprecated ``sheetname`` in favor of ``sheet_name`` for consistency with ``.to_excel()`` (:issue:`10559`).
491-
492491
- ``pd.options.html.border`` has been deprecated in favor of ``pd.options.display.html.border`` (:issue:`15793`).
493-
494492
- :func:`SeriesGroupBy.nth` has deprecated ``True`` in favor of ``'all'`` for its kwarg ``dropna`` (:issue:`11038`).
493+
- :func:`DataFrame.as_blocks` is deprecated, as this is exposing the internal implementation (:issue:`17302`)
495494

496495
.. _whatsnew_0210.prior_deprecations:
497496

pandas/core/computation/expressions.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ def _has_bool_dtype(x):
165165
return x.dtype == bool
166166
except AttributeError:
167167
try:
168-
return 'bool' in x.blocks
168+
return 'bool' in x.dtypes
169169
except AttributeError:
170170
return isinstance(x, (bool, np.bool_))
171171

pandas/core/generic.py

+25-22
Original file line numberDiff line numberDiff line change
@@ -3692,39 +3692,43 @@ def as_blocks(self, copy=True):
36923692
Convert the frame to a dict of dtype -> Constructor Types that each has
36933693
a homogeneous dtype.
36943694
3695+
.. deprecated:: 0.21.0
3696+
36953697
NOTE: the dtypes of the blocks WILL BE PRESERVED HERE (unlike in
36963698
as_matrix)
36973699
36983700
Parameters
36993701
----------
37003702
copy : boolean, default True
37013703
3702-
.. versionadded: 0.16.1
3703-
37043704
Returns
37053705
-------
37063706
values : a dict of dtype -> Constructor Types
37073707
"""
3708-
self._consolidate_inplace()
3709-
3710-
bd = {}
3711-
for b in self._data.blocks:
3712-
bd.setdefault(str(b.dtype), []).append(b)
3713-
3714-
result = {}
3715-
for dtype, blocks in bd.items():
3716-
# Must combine even after consolidation, because there may be
3717-
# sparse items which are never consolidated into one block.
3718-
combined = self._data.combine(blocks, copy=copy)
3719-
result[dtype] = self._constructor(combined).__finalize__(self)
3720-
3721-
return result
3708+
warnings.warn("as_blocks is deprecated and will "
3709+
"be removed in a future version",
3710+
FutureWarning, stacklevel=2)
3711+
return self._to_dict_of_blocks(copy=copy)
37223712

37233713
@property
37243714
def blocks(self):
3725-
"""Internal property, property synonym for as_blocks()"""
3715+
"""
3716+
Internal property, property synonym for as_blocks()
3717+
3718+
.. deprecated:: 0.21.0
3719+
"""
37263720
return self.as_blocks()
37273721

3722+
def _to_dict_of_blocks(self, copy=True):
3723+
"""
3724+
Return a dict of dtype -> Constructor Types that
3725+
each is a homogeneous dtype.
3726+
3727+
Internal ONLY
3728+
"""
3729+
return {k: self._constructor(v).__finalize__(self)
3730+
for k, v, in self._data.to_dict(copy=copy).items()}
3731+
37283732
@deprecate_kwarg(old_arg_name='raise_on_error', new_arg_name='errors',
37293733
mapping={True: 'raise', False: 'ignore'})
37303734
def astype(self, dtype, copy=True, errors='raise', **kwargs):
@@ -3931,13 +3935,12 @@ def convert_objects(self, convert_dates=True, convert_numeric=False,
39313935
-------
39323936
converted : same as input object
39333937
"""
3934-
from warnings import warn
39353938
msg = ("convert_objects is deprecated. To re-infer data dtypes for "
39363939
"object columns, use {klass}.infer_objects()\nFor all "
39373940
"other conversions use the data-type specific converters "
39383941
"pd.to_datetime, pd.to_timedelta and pd.to_numeric."
39393942
).format(klass=self.__class__.__name__)
3940-
warn(msg, FutureWarning, stacklevel=2)
3943+
warnings.warn(msg, FutureWarning, stacklevel=2)
39413944

39423945
return self._constructor(
39433946
self._data.convert(convert_dates=convert_dates,
@@ -4310,9 +4313,9 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
43104313
raise AssertionError("'to_replace' must be 'None' if 'regex' is "
43114314
"not a bool")
43124315
if axis is not None:
4313-
from warnings import warn
4314-
warn('the "axis" argument is deprecated and will be removed in'
4315-
'v0.13; this argument has no effect')
4316+
warnings.warn('the "axis" argument is deprecated '
4317+
'and will be removed in'
4318+
'v0.13; this argument has no effect')
43164319

43174320
self._consolidate_inplace()
43184321

pandas/core/internals.py

+25
Original file line numberDiff line numberDiff line change
@@ -3583,6 +3583,31 @@ def _interleave(self):
35833583

35843584
return result
35853585

3586+
def to_dict(self, copy=True):
3587+
"""
3588+
Return a dict of str(dtype) -> BlockManager
3589+
3590+
Parameters
3591+
----------
3592+
copy : boolean, default True
3593+
3594+
Returns
3595+
-------
3596+
values : a dict of dtype -> BlockManager
3597+
3598+
Notes
3599+
-----
3600+
This consolidates based on str(dtype)
3601+
"""
3602+
self._consolidate_inplace()
3603+
3604+
bd = {}
3605+
for b in self.blocks:
3606+
bd.setdefault(str(b.dtype), []).append(b)
3607+
3608+
return {dtype: self.combine(blocks, copy=copy)
3609+
for dtype, blocks in bd.items()}
3610+
35863611
def xs(self, key, axis=1, copy=True, takeable=False):
35873612
if axis < 1:
35883613
raise AssertionError('Can only take xs across axis >= 1, got %d' %

pandas/core/window.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ def _create_blocks(self, how):
141141
if obj.ndim == 2:
142142
obj = obj.reindex(columns=obj.columns.difference([self.on]),
143143
copy=False)
144-
blocks = obj.as_blocks(copy=False).values()
144+
blocks = obj._as_blocks(copy=False).values()
145145

146146
return blocks, obj, index
147147

pandas/tests/frame/test_block_internals.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,11 @@ def test_copy_blocks(self):
320320
column = df.columns[0]
321321

322322
# use the default copy=True, change a column
323-
blocks = df.as_blocks()
323+
324+
# deprecated 0.21.0
325+
with tm.assert_produces_warning(FutureWarning,
326+
check_stacklevel=False):
327+
blocks = df.as_blocks()
324328
for dtype, _df in blocks.items():
325329
if column in _df:
326330
_df.loc[:, column] = _df[column] + 1
@@ -334,7 +338,11 @@ def test_no_copy_blocks(self):
334338
column = df.columns[0]
335339

336340
# use the copy=False, change a column
337-
blocks = df.as_blocks(copy=False)
341+
342+
# deprecated 0.21.0
343+
with tm.assert_produces_warning(FutureWarning,
344+
check_stacklevel=False):
345+
blocks = df.as_blocks(copy=False)
338346
for dtype, _df in blocks.items():
339347
if column in _df:
340348
_df.loc[:, column] = _df[column] + 1

pandas/tests/frame/test_constructors.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1766,7 +1766,7 @@ def test_from_records_sequencelike(self):
17661766

17671767
# this is actually tricky to create the recordlike arrays and
17681768
# have the dtypes be intact
1769-
blocks = df.blocks
1769+
blocks = df._to_dict_of_blocks()
17701770
tuples = []
17711771
columns = []
17721772
dtypes = []
@@ -1841,8 +1841,9 @@ def test_from_records_dictlike(self):
18411841

18421842
# columns is in a different order here than the actual items iterated
18431843
# from the dict
1844+
blocks = df._to_dict_of_blocks()
18441845
columns = []
1845-
for dtype, b in compat.iteritems(df.blocks):
1846+
for dtype, b in compat.iteritems(blocks):
18461847
columns.extend(b.columns)
18471848

18481849
asdict = dict((x, y) for x, y in compat.iteritems(df))

pandas/tests/internals/test_internals.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -469,10 +469,11 @@ def test_set_change_dtype_slice(self): # GH8850
469469
df = DataFrame([[1.0, 2, 3], [4.0, 5, 6]], columns=cols)
470470
df['2nd'] = df['2nd'] * 2.0
471471

472-
assert sorted(df.blocks.keys()) == ['float64', 'int64']
473-
assert_frame_equal(df.blocks['float64'], DataFrame(
472+
blocks = df._to_dict_of_blocks()
473+
assert sorted(blocks.keys()) == ['float64', 'int64']
474+
assert_frame_equal(blocks['float64'], DataFrame(
474475
[[1.0, 4.0], [4.0, 10.0]], columns=cols[:2]))
475-
assert_frame_equal(df.blocks['int64'], DataFrame(
476+
assert_frame_equal(blocks['int64'], DataFrame(
476477
[[3], [6]], columns=cols[2:]))
477478

478479
def test_copy(self, mgr):

pandas/tests/sparse/test_frame.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1099,7 +1099,10 @@ def test_as_blocks(self):
10991099
df = SparseDataFrame({'A': [1.1, 3.3], 'B': [nan, -3.9]},
11001100
dtype='float64')
11011101

1102-
df_blocks = df.blocks
1102+
# deprecated 0.21.0
1103+
with tm.assert_produces_warning(FutureWarning,
1104+
check_stacklevel=False):
1105+
df_blocks = df.blocks
11031106
assert list(df_blocks.keys()) == ['float64']
11041107
tm.assert_frame_equal(df_blocks['float64'], df)
11051108

pandas/util/testing.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1385,8 +1385,8 @@ def assert_frame_equal(left, right, check_dtype=True,
13851385

13861386
# compare by blocks
13871387
if by_blocks:
1388-
rblocks = right.blocks
1389-
lblocks = left.blocks
1388+
rblocks = right._to_dict_of_blocks()
1389+
lblocks = left._to_dict_of_blocks()
13901390
for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))):
13911391
assert dtype in lblocks
13921392
assert dtype in rblocks

0 commit comments

Comments
 (0)