首页 > 解决方案 > 为什么我无法从另一个列表中的元素过滤的列表中选择某些元素?

问题描述

我有一个数据集,其中除其他列外,还有 3 列称为CLASS和。DURATIONGENDER

import pandas as pd
data = pd.read_csv('dataset.csv')
CLASS = data['CLASS']
DURATION = data['DURATION']
GENDER = data['GENDER']

CLASS包含 5 种类型的条目 - blank, 1, 2, 3, 4; DURATION包含-1(表示某些语义值)或某些正整数;并且GENDER包含MF。我可以像这样选择条目CLASSGENDER

CLASS[GENDER=='M']

但我无法在这样OCCUP_CLASS的持续时间内选择条目-1

CLASS[DURATION=='-1']

这是为什么?这是我得到的错误:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-56-604aed5ebca4> in <module>()
----> 1 CLASS[DURATION=='-1']

c:\users\h473\appdata\local\programs\python\python35\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    621         key = com._apply_if_callable(key, self)
    622         try:
--> 623             result = self.index.get_value(self, key)
    624 
    625             if not is_scalar(result):

c:\users\h473\appdata\local\programs\python\python35\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
   2558         try:
   2559             return self._engine.get_value(s, k,
-> 2560                                           tz=getattr(series.dtype, 'tz', None))
   2561         except KeyError as e1:
   2562             if len(self) > 0 and self.inferred_type in ['integer', 'boolean']:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()

pandas\_libs\index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()

KeyError: False

标签: pythonpython-3.xlistindexing

解决方案


也许最好不要一开始就将它们拆分为系列,而是在 Dataframe 上尝试:

import pandas as pd
data = pd.read_csv('dataset.csv')
data.loc[data['GENDER'] == 'M', 'CLASS']
data.loc[data['DURATION'] == -1, 'CLASS']

推荐阅读