@@ -167,7 +167,28 @@ def _get_loc(self, key: int, axis: int):
167
167
def _slice (self , obj , axis : int , kind = None ):
168
168
return self .obj ._slice (obj , axis = axis , kind = kind )
169
169
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
+
170
182
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
+
171
192
if self .axis is not None :
172
193
return self ._convert_tuple (key )
173
194
@@ -202,21 +223,6 @@ def _get_setitem_indexer(self, key):
202
223
def __setitem__ (self , key , value ):
203
224
if isinstance (key , tuple ):
204
225
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
220
226
else :
221
227
key = com .apply_if_callable (key , self .obj )
222
228
indexer = self ._get_setitem_indexer (key )
0 commit comments