首页 文章

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

提问于
浏览
9

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

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

NumpyProtocolHander:将结果直接反序列化为NumPy数组 . 这有助于与分析工具包(如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) .

我对熊猫的了解有限,我试图运行非常基本的功能:

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数组“转换”到能够使用Pandas .

1 回答

  • 7

    简短的回答是:

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

    rslt [0]为Python dict提供数据,可以轻松转换为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])
    

    Note: 如果查询很大,上述解决方案只会为您提供部分数据 . 所以你应该这样做:

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

相关问题