【问题标题】:Why am I not able to select some elements from a list filtered by elements in another list?为什么我无法从另一个列表中的元素过滤的列表中选择某些元素?
【发布时间】:2018-11-23 17:40:03
【问题描述】:

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

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 包含 M 或 F。我可以通过GENDER 选择CLASS 中的条目,如下所示:

CLASS[GENDER=='M']

但我无法在-1 的持续时间内选择OCCUP_CLASS 中的条目,如下所示:

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

【问题讨论】:

  • 键-1是否有可能是整数,而不是字符串?
  • 我也试过CLASS[DURATION==-1,但我得到了同样的错误。
  • 你能print(CLASS)那里有什么吗?
  • 数据集中有 102008 行,所以我不能在这里显示完整的输出。但就像我说的,CLASS 包含空格或 1 或 2 或 3 或 4。
  • 你可以试试CLASS[DURATION&gt;0]

标签: python python-3.x list indexing


【解决方案1】:

我无法复制,但你可以试试

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

# fill the nan value 
DURATION.fillna(0,inplace=True)
# using astype convert the value to int then compare
CLASS[DURATION].astype(int)>0

【讨论】:

  • DURATION.fillna(0,inplace=True) 给出错误AttributeError: 'list' object has no attribute 'fillna'
  • 为什么是type if list,应该是panda Series,你随便投吧
  • 不,除了我在问题中写的内容之外,我什么也没做。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 2018-07-14
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多