Pandas 和 Cassandra:numpy 数组格式不兼容

Pandas and Cassandra: numpy array format incompatibility

我正在使用 Python cassandra 驱动程序来连接和查询我们的 Cassandra 集群。

我想通过 Pandas 操作我的数据,cassandra 驱动程序的文档中有一个区域准确地提到了这一点: https://datastax.github.io/python-driver/api/cassandra/protocol.html

NumpyProtocolHander: deserializes results directly into NumPy arrays. This facilitates efficient integration with analysis toolkits such as Pandas.

按照上述说明并在 Cassandra 中执行 SELECT 查询,我可以看到输出(通过 type() 函数)为:

<class 'cassandra.cluster.ResultSet'>

遍历结果,打印一行的结果如下:

{u'reversals_rejected': array([0, 0]), u'revenue': array([ 0, 10]), u'reversals_revenue': array([0, 0]), u'rejected': array([3, 1]), u'impressions_positive': array([3, 3]), u'site_user_id': array([226226, 354608], dtype=int32), u'error': array([0, 0]), u'impressions_negative': array([0, 0]), u'accepted': array([0, 2])}

(我限制了查询结果,我正在处理大量数据 - 因此想使用 numpy 和 pandas)。

我对 Pandas 的了解有限,我尝试 运行 非常基本的功能:

rslt = cassandraSession.execute("SELECT accepted FROM table")

test = rslt[["accepted"]].head(1)

这会输出以下错误:

Traceback (most recent call last):
  File "/UserStats.py", line 27, in <module>
    test = rslt[["accepted"]].head(1)
  File "cassandra/cluster.py", line 3380, in cassandra.cluster.ResultSet.__getitem__ (cassandra/cluster.c:63998)
TypeError: list indices must be integers, not list

我理解错误,我只是不知道如何从这个假设的 numpy 数组 "transition" 到能够使用 Pandas.

简短的回答是:

df = pd.DataFrame(rslt[0])
test = df.head(1)

rslt[0] 以 Python 字典的形式为您提供数据,可以轻松将其转换为 Pandas 数据框。

完整的解决方案:

import pandas as pd
from cassandra.cluster import Cluster
from cassandra.protocol import NumpyProtocolHandler
from cassandra.query import tuple_factory

cluster = Cluster(
    contact_points=['your_ip'],
    )
session = cluster.connect('your_keyspace')
session.row_factory = tuple_factory
session.client_protocol_handler = NumpyProtocolHandler

prepared_stmt = session.prepare ( "SELECT * FROM ... WHERE ...;")
bound_stmt = prepared_stmt.bind([...])
rslt = session.execute(bound_stmt)
df = pd.DataFrame(rslt[0])

注意:如果查询很大,上面的解决方案只会得到你的部分数据。所以你应该这样做:

df = pd.DataFrame()
for r in rslt:
    df = df.append(r)