检查Cassandra的resultSet是否为空(Python)

时间:2018-07-05 00:35:03

标签: python pandas cassandra datastax

我正在运行类似

    def searchCassanadra(self):
    # Iterate over every pokemon
    for x in self.pokemon_list:
        # Query
        query = session.execute("SELECT pokemon_id FROM ds_pokedex.pokemon where pokemon_id=" + repr(x))

上面的代码返回了<class 'cassandra.cluster.ResultSet'>

我如何检查ResultSet是空的还是从Cassandra中填充的?

我在python中编码。 很抱歉出现新手问题。

如果我尝试做

         if query.current_rows:
            print 'y'
        else:
            print 'n'

我收到此错误

  

ValueError:DataFrame的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

看起来您的query._current_rows属性是一个熊猫DataFrame,因此,当您尝试运行query.current_rows时,无论ResultSet是否为空,总是会引发ValueError。

ResultSet的{​​{3}}中,我们看到current_rows函数正在寻找_current_rows属性的存在:

@property
def current_rows(self):
    """
    The list of current page rows. May be empty if the result was empty,
    or this is the last page.
    """
    return self._current_rows or []

如果上面的self._current_rows是熊猫DataFrame,它将始终返回ValueError。例如:

>>> data = {'col1': [1, 2], 'col2': [3, 4]}
>>> df = pd.DataFrame(data)
>>> df
   col1  col2
0     1     3
1     2     4
>>> df or []
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/src/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pandas/core/generic.py", line 1573, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> df = pd.DataFrame()
>>> df or []
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/src/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pandas/core/generic.py", line 1573, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

因此,要检查ResultSet中的pandas DataFrame是否包含数据,可以执行以下操作:

if not query._current_rows.empty:
        print 'y'
    else:
        print 'n'

(注意:我不知道您的session.row_factory是什么样子,但我假设它是根据Cassandra返回的行创建一个熊猫DataFrame,类似于Cassandra Driver docs的答案)

相关问题