Skip to content

Commit 0fa2911

Browse files
committed
CLN/BUG: fix ndarray assignment may cause unexpected cast
1 parent f26b049 commit 0fa2911

File tree

11 files changed

+311
-144
lines changed

11 files changed

+311
-144
lines changed

Diff for: doc/source/whatsnew/v0.19.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ Bug Fixes
5656
- Bug in ``MultiIndex.set_levels`` where illegal level values were still set after raising an error (:issue:`13754`)
5757
- Bug in ``DataFrame.to_json`` where ``lines=True`` and a value contained a ``}`` character (:issue:`14391`)
5858
- Bug in ``df.groupby`` causing an ``AttributeError`` when grouping a single index frame by a column and the index level (:issue`14327`)
59+
<<<<<<< f26b049786624ed983f2718687c23e3f1adbb670
5960
- Bug in ``df.groupby`` where ``TypeError`` raised when ``pd.Grouper(key=...)`` is passed in a list (:issue:`14334`)
6061
- Bug in ``pd.pivot_table`` may raise ``TypeError`` or ``ValueError`` when ``index`` or ``columns``
6162
is not scalar and ``values`` is not specified (:issue:`14380`)

Diff for: doc/source/whatsnew/v0.19.2.txt

+2
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ Bug Fixes
6060
- Bug in ``.to_clipboard()`` and Excel compat (:issue:`12529`)
6161

6262

63+
- Bug in assignment against datetime-like data with ``int`` may incorrectly converted to datetime-like (:issue:`14145`)
64+
- Bug in assignment against ``int64`` data with ``np.ndarray`` with ``float64`` dtype may keep ``int64`` dtype (:issue:`14001`)
6365

6466

6567

Diff for: pandas/core/frame.py

+8-14
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
import numpy.ma as ma
2525

2626
from pandas.types.cast import (_maybe_upcast,
27-
_infer_dtype_from_scalar,
27+
_cast_scalar_to_array,
2828
_possibly_cast_to_datetime,
2929
_possibly_infer_to_datetimelike,
3030
_possibly_convert_platform,
@@ -332,15 +332,10 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
332332
raise_with_traceback(exc)
333333

334334
if arr.ndim == 0 and index is not None and columns is not None:
335-
if isinstance(data, compat.string_types) and dtype is None:
336-
dtype = np.object_
337-
if dtype is None:
338-
dtype, data = _infer_dtype_from_scalar(data)
339-
340-
values = np.empty((len(index), len(columns)), dtype=dtype)
341-
values.fill(data)
342-
mgr = self._init_ndarray(values, index, columns, dtype=dtype,
343-
copy=False)
335+
values = _cast_scalar_to_array((len(index), len(columns)),
336+
data, dtype=dtype)
337+
mgr = self._init_ndarray(values, index, columns,
338+
dtype=values.dtype, copy=False)
344339
else:
345340
raise PandasError('DataFrame constructor not properly called!')
346341

@@ -454,7 +449,7 @@ def _get_axes(N, K, index=index, columns=columns):
454449
values = _prep_ndarray(values, copy=copy)
455450

456451
if dtype is not None:
457-
if values.dtype != dtype:
452+
if not is_dtype_equal(values.dtype, dtype):
458453
try:
459454
values = values.astype(dtype)
460455
except Exception as orig:
@@ -2672,9 +2667,8 @@ def reindexer(value):
26722667

26732668
else:
26742669
# upcast the scalar
2675-
dtype, value = _infer_dtype_from_scalar(value)
2676-
value = np.repeat(value, len(self.index)).astype(dtype)
2677-
value = _possibly_cast_to_datetime(value, dtype)
2670+
value = _cast_scalar_to_array(len(self.index), value)
2671+
value = _possibly_cast_to_datetime(value, value.dtype)
26782672

26792673
# return internal types directly
26802674
if is_extension_type(value):

Diff for: pandas/core/internals.py

+94-82
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
is_null_datelike_scalar)
4242
import pandas.types.concat as _concat
4343

44-
from pandas.types.generic import ABCSeries
44+
from pandas.types.generic import ABCSeries, ABCDatetimeIndex
4545
from pandas.core.common import is_null_slice
4646
import pandas.core.algorithms as algos
4747

@@ -377,7 +377,8 @@ def fillna(self, value, limit=None, inplace=False, downcast=None,
377377

378378
# fillna, but if we cannot coerce, then try again as an ObjectBlock
379379
try:
380-
values, _, value, _ = self._try_coerce_args(self.values, value)
380+
values, _, _, _ = self._try_coerce_args(self.values, value)
381+
# value may be converted to internal, thus drop
381382
blocks = self.putmask(mask, value, inplace=inplace)
382383
blocks = [b.make_block(values=self._try_coerce_result(b.values))
383384
for b in blocks]
@@ -665,8 +666,43 @@ def setitem(self, indexer, value, mgr=None):
665666
if self.is_numeric:
666667
value = np.nan
667668

668-
# coerce args
669-
values, _, value, _ = self._try_coerce_args(self.values, value)
669+
# coerce if block dtype can store value
670+
values = self.values
671+
try:
672+
values, _, value, _ = self._try_coerce_args(values, value)
673+
# can keep its own dtype
674+
if hasattr(value, 'dtype') and is_dtype_equal(values.dtype,
675+
value.dtype):
676+
dtype = self.dtype
677+
else:
678+
dtype = 'infer'
679+
680+
except (TypeError, ValueError):
681+
# current dtype cannot store value, coerce to common dtype
682+
find_dtype = False
683+
684+
if hasattr(value, 'dtype'):
685+
dtype = value.dtype
686+
find_dtype = True
687+
688+
elif is_scalar(value):
689+
if isnull(value):
690+
# NaN promotion is handled in latter path
691+
dtype = False
692+
else:
693+
dtype, _ = _infer_dtype_from_scalar(value,
694+
pandas_dtype=True)
695+
find_dtype = True
696+
else:
697+
dtype = 'infer'
698+
699+
if find_dtype:
700+
dtype = _find_common_type([values.dtype, dtype])
701+
if not is_dtype_equal(self.dtype, dtype):
702+
b = self.astype(dtype)
703+
return b.setitem(indexer, value, mgr=mgr)
704+
705+
# value must be storeable at this moment
670706
arr_value = np.array(value)
671707

672708
# cast the values to a type that can hold nan (if necessary)
@@ -696,87 +732,52 @@ def setitem(self, indexer, value, mgr=None):
696732
raise ValueError("cannot set using a slice indexer with a "
697733
"different length than the value")
698734

699-
try:
700-
701-
def _is_scalar_indexer(indexer):
702-
# return True if we are all scalar indexers
703-
704-
if arr_value.ndim == 1:
705-
if not isinstance(indexer, tuple):
706-
indexer = tuple([indexer])
707-
return all([is_scalar(idx) for idx in indexer])
708-
return False
709-
710-
def _is_empty_indexer(indexer):
711-
# return a boolean if we have an empty indexer
735+
def _is_scalar_indexer(indexer):
736+
# return True if we are all scalar indexers
712737

713-
if arr_value.ndim == 1:
714-
if not isinstance(indexer, tuple):
715-
indexer = tuple([indexer])
716-
return any(isinstance(idx, np.ndarray) and len(idx) == 0
717-
for idx in indexer)
718-
return False
719-
720-
# empty indexers
721-
# 8669 (empty)
722-
if _is_empty_indexer(indexer):
723-
pass
724-
725-
# setting a single element for each dim and with a rhs that could
726-
# be say a list
727-
# GH 6043
728-
elif _is_scalar_indexer(indexer):
729-
values[indexer] = value
730-
731-
# if we are an exact match (ex-broadcasting),
732-
# then use the resultant dtype
733-
elif (len(arr_value.shape) and
734-
arr_value.shape[0] == values.shape[0] and
735-
np.prod(arr_value.shape) == np.prod(values.shape)):
736-
values[indexer] = value
737-
values = values.astype(arr_value.dtype)
738-
739-
# set
740-
else:
741-
values[indexer] = value
742-
743-
# coerce and try to infer the dtypes of the result
744-
if hasattr(value, 'dtype') and is_dtype_equal(values.dtype,
745-
value.dtype):
746-
dtype = value.dtype
747-
elif is_scalar(value):
748-
dtype, _ = _infer_dtype_from_scalar(value)
749-
else:
750-
dtype = 'infer'
751-
values = self._try_coerce_and_cast_result(values, dtype)
752-
block = self.make_block(transf(values), fastpath=True)
753-
754-
# may have to soft convert_objects here
755-
if block.is_object and not self.is_object:
756-
block = block.convert(numeric=False)
757-
758-
return block
759-
except ValueError:
760-
raise
761-
except TypeError:
738+
if arr_value.ndim == 1:
739+
if not isinstance(indexer, tuple):
740+
indexer = tuple([indexer])
741+
return all([is_scalar(idx) for idx in indexer])
742+
return False
762743

763-
# cast to the passed dtype if possible
764-
# otherwise raise the original error
765-
try:
766-
# e.g. we are uint32 and our value is uint64
767-
# this is for compat with older numpies
768-
block = self.make_block(transf(values.astype(value.dtype)))
769-
return block.setitem(indexer=indexer, value=value, mgr=mgr)
744+
def _is_empty_indexer(indexer):
745+
# return a boolean if we have an empty indexer
770746

771-
except:
772-
pass
773-
774-
raise
747+
if arr_value.ndim == 1:
748+
if not isinstance(indexer, tuple):
749+
indexer = tuple([indexer])
750+
return any(isinstance(idx, np.ndarray) and len(idx) == 0
751+
for idx in indexer)
752+
return False
775753

776-
except Exception:
754+
# empty indexers
755+
# 8669 (empty)
756+
if _is_empty_indexer(indexer):
777757
pass
778758

779-
return [self]
759+
# setting a single element for each dim and with a rhs that could
760+
# be say a list
761+
# GH 6043
762+
elif _is_scalar_indexer(indexer):
763+
values[indexer] = value
764+
765+
# if we are an exact match (ex-broadcasting),
766+
# then use the resultant dtype
767+
elif (len(arr_value.shape) and
768+
arr_value.shape[0] == values.shape[0] and
769+
np.prod(arr_value.shape) == np.prod(values.shape)):
770+
values[indexer] = value
771+
values = values.astype(arr_value.dtype)
772+
773+
# set
774+
else:
775+
values[indexer] = value
776+
777+
# coerce and try to infer the dtypes of the result
778+
values = self._try_coerce_and_cast_result(values, dtype)
779+
block = self.make_block(transf(values), fastpath=True)
780+
return block
780781

781782
def putmask(self, mask, new, align=True, inplace=False, axis=0,
782783
transpose=False, mgr=None):
@@ -1241,6 +1242,7 @@ def func(cond, values, other):
12411242

12421243
values, values_mask, other, other_mask = self._try_coerce_args(
12431244
values, other)
1245+
12441246
try:
12451247
return self._try_coerce_result(expressions.where(
12461248
cond, values, other, raise_on_error=True))
@@ -1519,6 +1521,7 @@ def putmask(self, mask, new, align=True, inplace=False, axis=0,
15191521
new = new[mask]
15201522

15211523
mask = _safe_reshape(mask, new_values.shape)
1524+
15221525
new_values[mask] = new
15231526
new_values = self._try_coerce_result(new_values)
15241527
return [self.make_block(values=new_values)]
@@ -1688,7 +1691,7 @@ def fillna(self, value, **kwargs):
16881691

16891692
# allow filling with integers to be
16901693
# interpreted as seconds
1691-
if not isinstance(value, np.timedelta64) and is_integer(value):
1694+
if not isinstance(value, np.timedelta64):
16921695
value = Timedelta(value, unit='s')
16931696
return super(TimeDeltaBlock, self).fillna(value, **kwargs)
16941697

@@ -1920,6 +1923,15 @@ def _maybe_downcast(self, blocks, downcast=None):
19201923
def _can_hold_element(self, element):
19211924
return True
19221925

1926+
def _try_coerce_args(self, values, other):
1927+
""" provide coercion to our input arguments """
1928+
1929+
if isinstance(other, ABCDatetimeIndex):
1930+
# to store DatetimeTZBlock as object
1931+
other = other.asobject.values
1932+
1933+
return values, False, other, False
1934+
19231935
def _try_cast(self, element):
19241936
return element
19251937

@@ -2256,8 +2268,6 @@ def _try_coerce_args(self, values, other):
22562268
"naive Block")
22572269
other_mask = isnull(other)
22582270
other = other.asm8.view('i8')
2259-
elif hasattr(other, 'dtype') and is_integer_dtype(other):
2260-
other = other.view('i8')
22612271
else:
22622272
try:
22632273
other = np.asarray(other)
@@ -2433,6 +2443,8 @@ def _try_coerce_args(self, values, other):
24332443
raise ValueError("incompatible or non tz-aware value")
24342444
other_mask = isnull(other)
24352445
other = other.value
2446+
else:
2447+
raise TypeError
24362448

24372449
return values, values_mask, other, other_mask
24382450

Diff for: pandas/core/panel.py

+5-8
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import numpy as np
1010

1111
from pandas.types.cast import (_infer_dtype_from_scalar,
12+
_cast_scalar_to_array,
1213
_possibly_cast_item)
1314
from pandas.types.common import (is_integer, is_list_like,
1415
is_string_like, is_scalar)
@@ -166,11 +167,9 @@ def _init_data(self, data, copy, dtype, **kwargs):
166167
copy = False
167168
dtype = None
168169
elif is_scalar(data) and all(x is not None for x in passed_axes):
169-
if dtype is None:
170-
dtype, data = _infer_dtype_from_scalar(data)
171-
values = np.empty([len(x) for x in passed_axes], dtype=dtype)
172-
values.fill(data)
173-
mgr = self._init_matrix(values, passed_axes, dtype=dtype,
170+
values = _cast_scalar_to_array([len(x) for x in passed_axes],
171+
data, dtype=dtype)
172+
mgr = self._init_matrix(values, passed_axes, dtype=values.dtype,
174173
copy=False)
175174
copy = False
176175
else: # pragma: no cover
@@ -570,9 +569,7 @@ def __setitem__(self, key, value):
570569
shape[1:], tuple(map(int, value.shape))))
571570
mat = np.asarray(value)
572571
elif is_scalar(value):
573-
dtype, value = _infer_dtype_from_scalar(value)
574-
mat = np.empty(shape[1:], dtype=dtype)
575-
mat.fill(value)
572+
mat = _cast_scalar_to_array(shape[1:], value)
576573
else:
577574
raise TypeError('Cannot set item of type: %s' % str(type(value)))
578575

0 commit comments

Comments
 (0)