python - 为什么我无法从另一个列表中的元素过滤的列表中选择某些元素?
问题描述
我有一个数据集,其中除其他列外,还有 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
。我可以像这样选择条目CLASS
:GENDER
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
解决方案
也许最好不要一开始就将它们拆分为系列,而是在 Dataframe 上尝试:
import pandas as pd
data = pd.read_csv('dataset.csv')
data.loc[data['GENDER'] == 'M', 'CLASS']
data.loc[data['DURATION'] == -1, 'CLASS']
推荐阅读
- asp.net-mvc - ASP.NET Core Image 上传 POST 请求到 API
- node.js - 使用聚合或使用 nodejs 和 mongoose 手动过滤数据是否更快?
- mongodb - 使用 docker-compose 启动 mongo docker
- r - 桑基图有序年
- python - 提前停止 TensorFlow 对象检测 API
- javascript - 页面加载时 Chartjs 条形图显示为空
- python - python 27的eric安装
- kotlin - 如何让 ktor netty 服务器使用 CachedThreadPool 来处理请求?
- python - 用另一个返回 NoneType 的有效列表扩展 1 元素列表
- javascript - 使用 file.save() 将图像上传到 Google Cloud Storage。一切似乎都成功,但图像不起作用