重塑列表以编写选择语句

时间:2019-12-07 21:16:13

标签: python pandas dataframe

我有一个这种格式的数据框: enter image description here

,我想根据其他操作的先前输出选择具有特定类的行,问题是先前的输出格式如下 most=["['books']"],所以当我尝试编写select语句时,它是这样写的:

df.loc[str([df['class'][0]])==most[0]]

但是,我收到此错误:

~\Anaconda3\mianaconda\lib\site-packages\pandas\core\indexing.py in _validate_key(self, key, axis)
   1789                 if not ax.contains(key):
-> 1790                     error()
   1791             except TypeError as e:

~\Anaconda3\mianaconda\lib\site-packages\pandas\core\indexing.py in error()
   1784                                .format(key=key,
-> 1785                                        axis=self.obj._get_axis_name(axis)))
   1786 

KeyError: 'the label [True] is not in the [index]'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-166-604a94f3536a> in <module>
----> 1 df.loc[str([df['class'][0]])==most[0]]

~\Anaconda3\mianaconda\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1476 
   1477             maybe_callable = com._apply_if_callable(key, self.obj)
-> 1478             return self._getitem_axis(maybe_callable, axis=axis)
   1479 
   1480     def _is_scalar_access(self, key):

~\Anaconda3\mianaconda\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1909 
   1910         # fall thru to straight lookup
-> 1911         self._validate_key(key, axis)
   1912         return self._get_label(key, axis=axis)
   1913 

~\Anaconda3\mianaconda\lib\site-packages\pandas\core\indexing.py in _validate_key(self, key, axis)
   1796                 raise
   1797             except:
-> 1798                 error()
   1799 
   1800     def _is_scalar_access(self, key):

~\Anaconda3\mianaconda\lib\site-packages\pandas\core\indexing.py in error()
   1783                 raise KeyError(u"the label [{key}] is not in the [{axis}]"
   1784                                .format(key=key,
-> 1785                                        axis=self.obj._get_axis_name(axis)))
   1786 
   1787             try:

KeyError: 'the label [True] is not in the [index]'

我该如何解决?

1 个答案:

答案 0 :(得分:1)

尝试一下:

 df.loc[df['class'] == eval(most[0])[0]] 

您的字符串必须转换为数组,然后查找以在数组中获取字符串,即字符串。