使用由布尔索引创建的数据框时出错

Error using a dataframe created by a boolean indexing

编辑

我有这个数据框:

df = pd.DataFrame({'a':['nonono','sisisis','some_other_string', 'blebleble', 
                        'jajajaja', 'ohyeah','some_string','blablablananana'], 
                   'b':[0,1,2,3,4,5,6,7]})

正如 docs 所说,我已经创建了一个布尔索引来创建一个新的数据框。

df2 = df.loc[df.a != 'some_string', :]

为了检查我制作的数据帧的长度差异 print(len(df) > len(df2)) 和输出是 True。这意味着布尔索引正确,不是吗?

但是,当我训练根据某些条件打印 True 或 False 时,它​​会引发 KeyError: 6。这是代码:

for i in list(range(len(df2.a))):
  if 'blabla' in df2.a[i]:
    print(True)
  else:
    print(False)

输出为

False
False
False
False
False
False
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-85-2c4113790af5> in <module>()
      1 for i in list(range(len(facturacion.formulario))):
----> 2   if 'NOTA DE CREDITO' in facturacion.formulario[i]:
      3     print(True)
      4   else:
      5     print(False)

1 frames
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_value(self, series, key)
   4403         k = self._convert_scalar_indexer(k, kind="getitem")
   4404         try:
-> 4405             return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
   4406         except KeyError as e1:
   4407             if len(self) > 0 and (self.holds_integer() or self.is_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.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 6

如果我做

for i in list(range(len(df2.a[:6]))):
  if 'blabla' in df2.a[i]:
    print(True)
  else:
    print(False)

输出为

False
False
False
False
False
False

我不知道发生了什么。有什么建议吗?

我认为这是问题所在:

df2.a[i]

您的第 6 个索引在编制索引时被删除

df2 = df.loc[df.a != 'some_string', :]

您应该重置索引:

df2.reset_index(drop=True)

或者你应该使用 loc:

df2.a.loc[i]