与 DataFrame 不兼容的索引器

Incompatible indexer with DataFrame

我试图根据另一列的条件在一列中设置值(HomePlanet 是一列,RoomService 是另一列):

     test.loc[test.HomePlanet == 1, 'RoomService'] = test.fillna(135)

我收到一个错误:

 ---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_2477/695172142.py in <module>
----> 1 test.loc[test.HomePlanet == 1, 'RoomService'] = test.fillna(135)

~/anaconda3/lib/python3.9/site-packages/pandas/core/indexing.py in __setitem__(self, key, value)
721 
722         iloc = self if self.name == "iloc" else self.obj.iloc
--> 723         iloc._setitem_with_indexer(indexer, value, self.name)
724 
725     def _validate_key(self, key, axis: int):

~/anaconda3/lib/python3.9/site-packages/pandas/core/indexing.py 
in _setitem_with_indexer(self, indexer, value, name)

1730             self._setitem_with_indexer_split_path(indexer, value, name)
1731         else:
-> 1732             self._setitem_single_block(indexer, value, name)
1733 
1734     def _setitem_with_indexer_split_path(self, indexer, value, name: str):

~/anaconda3/lib/python3.9/site-packages/pandas/core/indexing.py in _setitem_single_block(self, indexer, value, name)
1960 
1961         elif isinstance(value, ABCDataFrame) and name != "iloc":
-> 1962             value = self._align_frame(indexer, value)
1963 
1964         # check for chained assignment

~/anaconda3/lib/python3.9/site-packages/pandas/core/indexing.py in _align_frame(self, indexer, df)
2199             return val
2200 
-> 2201         raise ValueError("Incompatible indexer with DataFrame")
2202 
2203 

ValueError: Incompatible indexer with DataFrame

令人困惑的是,我对其他类似的数据做了同样的事情,但没有问题。 有谁知道如何解决这个问题?

这是我的数据框的信息:

 <class 'pandas.core.frame.DataFrame'>
  RangeIndex: 4277 entries, 0 to 4276
  Data columns (total 10 columns):
  #   Column        Non-Null Count  Dtype  
 ---  ------        --------------  -----  
  0   HomePlanet    4190 non-null   float64
  1   CryoSleep     4184 non-null   float64
  2   Destination   4185 non-null   float64
  3   Age           4186 non-null   float64
  4   VIP           4184 non-null   float64
  5   RoomService   4195 non-null   float64
  6   FoodCourt     4171 non-null   float64
  7   ShoppingMall  4179 non-null   float64
  8   Spa           4176 non-null   float64
  9   VRDeck        4197 non-null   float64
  dtypes: float64(10)
  memory usage: 334.3 KB

由于您只想在 RoomService 列中填写,您可以

test.loc[test.HomePlanet == 1, 'RoomService'] = test['RoomService'].fillna(135)