【问题标题】:Check if Cassandra's resultSet is empty or not (Python)检查 Cassandra 的结果集是否为空(Python)
【发布时间】:2018-12-13 09:21:08
【问题描述】:

我正在运行类似的东西

    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()。

感谢您的帮助。

【问题讨论】:

标签: python pandas cassandra datastax


【解决方案1】:

看起来你的query._current_rows 属性是一个pandas DataFrame,所以当你尝试运行query.current_rows 时,总会引发ValueError,不管ResultSet 是否为空。

ResultSetCassandra Driver docs 中,我们看到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 是一个pandas 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 返回的行创建一个pandas DataFrame,类似于this 答案)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-09
    • 2014-04-13
    • 2018-03-24
    • 1970-01-01
    • 2013-07-24
    • 2014-04-13
    相关资源
    最近更新 更多