Skip to content

Commit 3ee768c

Browse files
committed
Refactor code
1 parent 26bd7cd commit 3ee768c

File tree

2 files changed

+22
-21
lines changed

2 files changed

+22
-21
lines changed

pandas/core/frame.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3007,12 +3007,7 @@ def _setitem_array(self, key, value):
30073007
for k1, k2 in zip(key, value.columns):
30083008
self[k1] = value[k2]
30093009
else:
3010-
if all(is_hashable(k) for k in key):
3011-
for k in key:
3012-
try:
3013-
self[k]
3014-
except KeyError:
3015-
self[k] = np.nan
3010+
self.loc._ensure_listlike_indexer(key, axis=1)
30163011
indexer = self.loc._get_listlike_indexer(
30173012
key, axis=1, raise_missing=False
30183013
)[1]

pandas/core/indexing.py

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,28 @@ def _get_loc(self, key: int, axis: int):
167167
def _slice(self, obj, axis: int, kind=None):
168168
return self.obj._slice(obj, axis=axis, kind=kind)
169169

170+
def _ensure_listlike_indexer(self, key, axis):
171+
# if `key` is an index to multiple columns by name, add each column
172+
# if it does not already exist
173+
if not isinstance(self.obj._get_axis(axis), ABCMultiIndex) and all(
174+
is_hashable(k) for k in key
175+
):
176+
for k in key:
177+
try:
178+
self.obj[k]
179+
except KeyError:
180+
self.obj[k] = np.nan
181+
170182
def _get_setitem_indexer(self, key):
183+
if (
184+
self.name == "loc" # column is indexed by name
185+
and isinstance(key, tuple)
186+
and len(key) >= 2 # key is at least 2-dimensional
187+
and is_list_like_indexer(key[1]) # key indexes multiple columns
188+
and not com.is_bool_indexer(key[1])
189+
):
190+
self._ensure_listlike_indexer(key[1], axis=1)
191+
171192
if self.axis is not None:
172193
return self._convert_tuple(key)
173194

@@ -202,21 +223,6 @@ def _get_setitem_indexer(self, key):
202223
def __setitem__(self, key, value):
203224
if isinstance(key, tuple):
204225
key = tuple(com.apply_if_callable(x, self.obj) for x in key)
205-
# if `key` is an index to multiple columns by name, add each column
206-
# if it does not already exist
207-
if (
208-
self.name == "loc" # column is indexed by name
209-
and len(key) >= 2 # key is at least 2-dimensional
210-
and is_list_like_indexer(key[1]) # key indexes multiple columns
211-
and not isinstance(self.obj._get_axis(1), ABCMultiIndex)
212-
and not com.is_bool_indexer(key[1])
213-
and all(is_hashable(k) for k in key[1])
214-
):
215-
for k in key[1]:
216-
try:
217-
self.obj[k]
218-
except KeyError:
219-
self.obj[k] = np.nan
220226
else:
221227
key = com.apply_if_callable(key, self.obj)
222228
indexer = self._get_setitem_indexer(key)

0 commit comments

Comments
 (0)