在泰坦尼克号数据集中,问题是找到幸存的男性乘客,我找不到正确的输出

问题描述 投票:0回答:1

[titanic_train.iloc[np.where(titanic_train["Sex"] == 'male')]["Survived"] == 1]
该行根据 true false 条件给出了正确的输出,但在从文本数据集中提取名称 col 时给出了错误
titanic_train[titanic_train.iloc[np.where(titanic_train["Sex"] == 'male')]["Survived"] == 1]

错误

IndexingError                             Traceback (most recent call last)
Cell In[87], line 1
----> 1 titanic_train[titanic_train.iloc[np.where(titanic_train["Sex"] == 'male')]["Survived"] == 1]

File C:\ProgramData\anaconda3\lib\site-packages\pandas\core\frame.py:3798, in DataFrame.__getitem__(self, key)
   3796 # Do we have a (boolean) 1d indexer?
   3797 if com.is_bool_indexer(key):
-> 3798     return self._getitem_bool_array(key)
   3800 # We are left with two options: a single key, and a collection of keys,
   3801 # We interpret tuples as collections only for non-MultiIndex
   3802 is_single_key = isinstance(key, tuple) or not is_list_like(key)

File C:\ProgramData\anaconda3\lib\site-packages\pandas\core\frame.py:3851, in DataFrame._getitem_bool_array(self, key)
   3845     raise ValueError(
   3846         f"Item wrong length {len(key)} instead of {len(self.index)}."
   3847     )
   3849 # check_bool_indexer will throw exception if Series key cannot
   3850 # be reindexed to match DataFrame rows
-> 3851 key = check_bool_indexer(self.index, key)
   3852 indexer = key.nonzero()[0]
   3853 return self._take_with_is_copy(indexer, axis=0)

File C:\ProgramData\anaconda3\lib\site-packages\pandas\core\indexing.py:2552, in check_bool_indexer(index, key)
   2550 indexer = result.index.get_indexer_for(index)
   2551 if -1 in indexer:
-> 2552     raise IndexingError(
   2553         "Unalignable boolean Series provided as "
   2554         "indexer (index of the boolean Series and of "
   2555         "the indexed object do not match)."
   2556     )
   2558 result = result.take(indexer)
   2560 # fall through for boolean

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

从上面的代码中提取名称

pandas dataframe machine-learning dataset
1个回答
0
投票

不太清楚你想要什么,但尝试 .query()

代码:

titanic_train = titanic_train.query(expr="Sex.eq('male') & Survived.eq(1)")
© www.soinside.com 2019 - 2024. All rights reserved.