Skip to content

Commit ce7670c

Browse files
authored
Implement BlockManager.iset (#32350)
1 parent d206479 commit ce7670c

File tree

1 file changed

+24
-10
lines changed

1 file changed

+24
-10
lines changed

pandas/core/internals/managers.py

+24-10
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import numpy as np
99

1010
from pandas._libs import Timedelta, Timestamp, internals as libinternals, lib
11-
from pandas._typing import DtypeObj
11+
from pandas._typing import DtypeObj, Label
1212
from pandas.util._validators import validate_bool_kwarg
1313

1414
from pandas.core.dtypes.cast import (
@@ -1001,7 +1001,25 @@ def delete(self, item):
10011001
)
10021002
self._rebuild_blknos_and_blklocs()
10031003

1004-
def set(self, item, value):
1004+
def set(self, item: Label, value):
1005+
"""
1006+
Set new item in-place.
1007+
1008+
Notes
1009+
-----
1010+
Does not consolidate.
1011+
Adds new Block if not contained in the current items Index.
1012+
"""
1013+
try:
1014+
loc = self.items.get_loc(item)
1015+
except KeyError:
1016+
# This item wasn't present, just insert at end
1017+
self.insert(len(self.items), item, value)
1018+
return
1019+
1020+
self.iset(loc, value)
1021+
1022+
def iset(self, loc: Union[int, slice, np.ndarray], value):
10051023
"""
10061024
Set new item in-place. Does not consolidate. Adds new Block if not
10071025
contained in the current set of items
@@ -1034,13 +1052,6 @@ def value_getitem(placement):
10341052
"Shape of new values must be compatible with manager shape"
10351053
)
10361054

1037-
try:
1038-
loc = self.items.get_loc(item)
1039-
except KeyError:
1040-
# This item wasn't present, just insert at end
1041-
self.insert(len(self.items), item, value)
1042-
return
1043-
10441055
if isinstance(loc, int):
10451056
loc = [loc]
10461057

@@ -1086,7 +1097,7 @@ def value_getitem(placement):
10861097
unfit_mgr_locs = np.concatenate(unfit_mgr_locs)
10871098
unfit_count = len(unfit_mgr_locs)
10881099

1089-
new_blocks = []
1100+
new_blocks: List[Block] = []
10901101
if value_is_extension_type:
10911102
# This code (ab-)uses the fact that sparse blocks contain only
10921103
# one item.
@@ -1145,6 +1156,9 @@ def insert(self, loc: int, item, value, allow_duplicates: bool = False):
11451156
# insert to the axis; this could possibly raise a TypeError
11461157
new_axis = self.items.insert(loc, item)
11471158

1159+
if value.ndim == self.ndim - 1 and not is_extension_array_dtype(value):
1160+
value = _safe_reshape(value, (1,) + value.shape)
1161+
11481162
block = make_block(values=value, ndim=self.ndim, placement=slice(loc, loc + 1))
11491163

11501164
for blkno, count in _fast_count_smallints(self._blknos[loc:]):

0 commit comments

Comments
 (0)