索引错误:不可对齐的布尔级数

2024-10-01 07:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码中出现索引错误

data.loc[data.loc[sub_df_idx, 'A'] == data.loc[sub_df_idx, 'A'].min(), 'B']

sub_df_idx只是

Int64Index([25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
            42, 43, 44, 45, 46, 47, 48],
           dtype='int64')

错误如下所示

---------------------------------------------------------------------------
IndexingError                             Traceback (most recent call last)
<ipython-input-133-166fca4d6d06> in <module>
----> 1 data.loc[data.loc[sub_df_idx, 'A'] == data.loc[sub_df_idx, 'A'].min(), 'B']

c:\users\hitesh vijay somani\appdata\local\programs\python\python38-32\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1760                 except (KeyError, IndexError, AttributeError):
   1761                     pass
-> 1762             return self._getitem_tuple(key)
   1763         else:
   1764             # we by definition only have the 0th axis

c:\users\hitesh vijay somani\appdata\local\programs\python\python38-32\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
   1287                 continue
   1288 
-> 1289             retval = getattr(retval, self.name)._getitem_axis(key, axis=i)
   1290 
   1291         return retval

c:\users\hitesh vijay somani\appdata\local\programs\python\python38-32\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1912             return self._get_slice_axis(key, axis=axis)
   1913         elif com.is_bool_indexer(key):
-> 1914             return self._getbool_axis(key, axis=axis)
   1915         elif is_list_like_indexer(key):
   1916 

c:\users\hitesh vijay somani\appdata\local\programs\python\python38-32\lib\site-packages\pandas\core\indexing.py in _getbool_axis(self, key, axis)
   1780         # caller is responsible for ensuring non-None axis
   1781         labels = self.obj._get_axis(axis)
-> 1782         key = check_bool_indexer(labels, key)
   1783         inds = key.nonzero()[0]
   1784         return self.obj._take_with_is_copy(inds, axis=axis)

c:\users\hitesh vijay somani\appdata\local\programs\python\python38-32\lib\site-packages\pandas\core\indexing.py in check_bool_indexer(index, key)
   2315         mask = isna(result._values)
   2316         if mask.any():
-> 2317             raise IndexingError(
   2318                 "Unalignable boolean Series provided as "
   2319                 "indexer (index of the boolean Series and of "

IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

Tags: keyinselfdfdatalocalusersappdata
1条回答
网友
1楼 · 发布于 2024-10-01 07:35:26

掩码的索引必须与原始索引长度相同,因此请比较原始列A,然后通过^{}仅筛选来自sub_df_idx的索引值:

data.loc[(data['A'] == data.loc[sub_df_idx, 'A'].min()) & df.index.isin(sub_df_idx), 'B']

或者首先按sub_df_idx筛选行,然后按min值筛选行:

df = data.loc[sub_df_idx]
df.loc[df['A'] == df[ 'A'].min(),  'B']

相关问题 更多 >