[Python] pandas .loc(): "TypeError: Must provide strings" only on third occurrence

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    I apply the following code to dataframe model_data_utsset (size (36484909, 113) - thoughts on making this publicly available for problem reproduction are welcome.) The same application of .loc() works fine for the third and fourth lines of code, but the fifth (final) line returns TypeError: Must provide strings. (Complete traceback at the end.) I have verified that the list feats contains only strings, and that the dataframe returned by .loc() has the same shape as the array dummy. Pandas version is 2.2.0.

    How can I resolve this error?

    from sklearn.preprocessing import RobustScaler
    scaler = RobustScaler()
    trans = scaler.fit(model_data_utsset.loc[model_data_utsset['cmdb_ci']==ci, feats])
    dummy = trans.transform(model_data_utsset.loc[ model_data_utsset['cmdb_ci']==ci, feats])
    model_data_utsset.loc[model_data_utsset['cmdb_ci']==ci, feats] = dummy


    ---------------------------------------------------------------------------
    TypeError Traceback (most recent call last)
    /tmp/ipykernel_3506448/3789644235.py in <module>
    5 dummy = trans.transform(model_data_utsset.loc[ model_data_utsset['cmdb_ci']==ci, feats])
    ----> 6 model_data_utsset.loc[model_data_utsset['cmdb_ci']==ci, feats] = dummy
    7 print(len(model_data_utsset.loc[model_data_utsset['cmdb_ci']==ci, feats]))

    ~/.local/lib/python3.9/site-packages/pandas/core/indexing.py in __setitem__(self, key, value)
    910
    911 iloc = self if self.name == "iloc" else self.obj.iloc
    --> 912 iloc._setitem_with_indexer(indexer, value, self.name)
    913
    914 def _validate_key(self, key, axis: AxisInt):

    ~/.local/lib/python3.9/site-packages/pandas/core/indexing.py in _setitem_with_indexer(self, indexer, value, name)
    1944 if take_split_path:
    1945 # We have to operate column-wise
    -> 1946 self._setitem_with_indexer_split_path(indexer, value, name)
    1947 else:
    1948 self._setitem_single_block(indexer, value, name)

    ~/.local/lib/python3.9/site-packages/pandas/core/indexing.py in _setitem_with_indexer_split_path(self, indexer, value, name)
    1984 # TODO: avoid np.ndim call in case it isn't an ndarray, since
    1985 # that will construct an ndarray, which will be wasteful
    -> 1986 self._setitem_with_indexer_2d_value(indexer, value)
    1987
    1988 elif len(ilocs) == 1 and lplane_indexer == len(value) and not is_scalar(pi):

    ~/.local/lib/python3.9/site-packages/pandas/core/indexing.py in _setitem_with_indexer_2d_value(self, indexer, value)
    2059 # casting to list so that we do type inference in setitem_single_column
    2060 value_col = value_col.tolist()
    -> 2061 self._setitem_single_column(loc, value_col, pi)
    2062
    2063 def _setitem_with_indexer_frame_value(self, indexer, value: DataFrame, name: str):

    ~/.local/lib/python3.9/site-packages/pandas/core/indexing.py in _setitem_single_column(self, loc, value, plane_indexer)
    2166 # set value into the column (first attempting to operate inplace, then
    2167 # falling back to casting if necessary)
    -> 2168 self.obj._mgr.column_setitem(loc, plane_indexer, value)
    2169
    2170 self.obj._clear_item_cache()

    ~/.local/lib/python3.9/site-packages/pandas/core/internals/managers.py in column_setitem(self, loc, idx, value, inplace_only)
    1336 col_mgr.setitem_inplace(idx, value)
    1337 else:
    -> 1338 new_mgr = col_mgr.setitem((idx,), value)
    1339 self.iset(loc, new_mgr._block.values, inplace=True)
    1340

    ~/.local/lib/python3.9/site-packages/pandas/core/internals/managers.py in setitem(self, indexer, value, warn)
    414 self = self.copy()
    415
    --> 416 return self.apply("setitem", indexer=indexer, value=value)
    417
    418 def diff(self, n: int) -> Self:

    ~/.local/lib/python3.9/site-packages/pandas/core/internals/managers.py in apply(self, f, align_keys, **kwargs)
    362 applied = b.apply(f, **kwargs)
    363 else:
    --> 364 applied = getattr(b, f)(**kwargs)
    365 result_blocks = extend_blocks(applied, result_blocks)
    366

    ~/.local/lib/python3.9/site-packages/pandas/core/internals/blocks.py in setitem(self, indexer, value, using_cow)
    2054
    2055 try:
    -> 2056 values[indexer] = value
    2057 except (ValueError, TypeError):
    2058 if isinstance(self.dtype, IntervalDtype):

    ~/.local/lib/python3.9/site-packages/pandas/core/arrays/string_.py in __setitem__(self, key, value)
    467 value = np.asarray(value, dtype=object)
    468 if len(value) and not lib.is_string_array(value, skipna=True):
    --> 469 raise TypeError("Must provide strings.")
    470
    471 mask = isna(value)

    TypeError: Must provide strings.

    Continue reading...

Compartilhe esta Página