0
試圖查詢數據幀Python的大熊貓:查詢失敗KeyError異常的一列了很多
In [6]: books.dtypes
Out[6]:
count float64
product int64
channel int64
book_start_year int64
book_start_week int64
book_end_year int64
book_end_week int64
period float64
dtype: object
In [8]: print(books.columns.tolist())
['count', 'product', 'channel', 'book_start_year', 'book_start_week', 'book_end_year', 'book_end_week', 'period']
有:
books[books.channel == 1]
工作正常,但是這一個:
books[books.product == 1]
失敗KeyError(請參閱下文)。數據幀根據前面大熊貓書面只需一分鐘前在MacOS下使用命令csv文件閱讀:
books = pd.read_csv('boxes2.csv', header=0)
復位或設置索引的另一列也沒有幫助。有任何想法嗎?
更新
我怎麼那麼應該寫這樣的查詢:
data = books[(books.start_year >= start_year)
& (books.start_week >= start_week)
& (books.end_year <= end_year)
& (books.end_week <= end_week)
& (books.product == product)
]
或者我可以不?
錯誤:
In [5]: books[books.product == 1]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-5-c6883f7202ed> in <module>()
----> 1 books[books.product == 1]
/Users/user/usr/anaconda_2.7/anaconda/lib/python2.7/site-packages/pandas/core/frame.pyc in _getitem_column(self, key)
2002 # get column
2003 if self.columns.is_unique:
-> 2004 return self._get_item_cache(key)
2005
2006 # duplicate columns & possible reduce dimensionality
/Users/user/usr/anaconda_2.7/anaconda/lib/python2.7/site-packages/pandas/core/generic.pyc in _get_item_cache(self, item\
)
1348 res = cache.get(item)
1349 if res is None:
-> 1350 values = self._data.get(item)
1351 res = self._book_item_values(item, values)
1352 cache[item] = res
/Users/user/usr/anaconda_2.7/anaconda/lib/python2.7/site-packages/pandas/core/internals.pyc in get(self, item, fastpath\
)
3288
3289 if not isnull(item):
-> 3290 loc = self.items.get_loc(item)
3291 else:
3292 indexer = np.arange(len(self.items))[isnull(self.items)]
/Users/user/usr/anaconda_2.7/anaconda/lib/python2.7/site-packages/pandas/indexes/base.pyc in get_loc(self, key, method,\
tolerance)
1945 return self._engine.get_loc(key)
1946 except KeyError:
-> 1947 return self._engine.get_loc(self._maybe_cast_indexer(key))
1948
1949 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4154)()
pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4018)()
pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12368)()
pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12322)()
KeyError: False
請看我更新的問題 – zork
查看更新的答案 – EdChum
這樣的答案值得高調投票 – piRSquared