【发布时间】:2021-01-05 07:27:45
【问题描述】:
我有一个名为“dt”的 Pandas DataFrame,它有两列名为“A”和“B”。 'B' 列的值是 numpy 数组;像这样的:
index A B
0 a [1,2,3]
1 b [2,3,4]
2 c [3,4,5]
地点:
type (dt["B"][0])
返回:numpy.ndarray
我想过滤此 DataFrame 以获得另一个 DataFrame,其中仅存在存储在 'B' 中的 numpy 数组中具有特定元素的行。
我试过了:
dt [element in dt["B"]]
例如:
dt [2 in dt["B"]]
应该返回:
index A B
0 a [1,2,3]
1 b [2,3,4]
但这会导致错误,即“KeyError: True”
如果“B”列的值是字符串,我可以做同样的事情而不会出错:
dt [dt["B"]==value]
所以我想知道为什么我的代码不起作用,“KeyError: True”是什么意思。
完整的错误是这样的:
KeyError Traceback (most recent call last)
~/Applications/Conda/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2645 try:
-> 2646 return self._engine.get_loc(key)
2647 except KeyError:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: True
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-151-aa9ea046a48f> in <module>
----> 1 quotes_of_base["BTC" in quotes_of_base["quote"]]
~/Applications/Conda/lib/python3.7/site-packages/pandas/core/frame.py in __getitem__(self, key)
2798 if self.columns.nlevels > 1:
2799 return self._getitem_multilevel(key)
-> 2800 indexer = self.columns.get_loc(key)
2801 if is_integer(indexer):
2802 indexer = [indexer]
~/Applications/Conda/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2646 return self._engine.get_loc(key)
2647 except KeyError:
-> 2648 return self._engine.get_loc(self._maybe_cast_indexer(key))
2649 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
2650 if indexer.ndim > 1 or indexer.size > 1:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: True
【问题讨论】:
-
使用
isin而不是in如下:dt[dt["B"].isin(element)]
标签: python pandas dataframe conditional-statements filtering