将Cassandra OrderedMapSerializedKey转换为Python字典

Ign*_*sel 5 python cassandra python-3.x pandas

我在Cassandra中有一列,由一列列表构成,当使用Python驱动程序查询时,它返回一个OrderedMapSerializedKey结构。此结构是列表的映射。我想将整个查询放入大熊猫中。

要从该OrderedMapSerializedKey结构中提取数据,这意味着获取键并将其用作新列的标签,并且仅将列表的第一个元素保留为值,我使用此处提到的方法,其中进行了一些复杂/肮脏的操作返回生成的DataFrame之前的工厂。

在这里提出类似的问题,但没有真正的答案。

有没有更好的方法可以将这样的OrderedMapSerializedKey结构转换为可以轻松加载到pandas DataFrame中的Python字典?

rag*_*esz 3

我认为最终的解决方案可能是存储OrderedMapSerializedKeyCassandra 结构存储为dict数据框列中的 a,然后您可以将此值/列传输给您想要的任何人。最终是因为您可能不知道 Cassandra 行中的实际键(可能将不同的键插入到行中)。

所以这里我测试过的解决方案,你只需要改进pandas_factory功能:


编辑:

在之前的解决方案中,我仅替换了 Cassandra 数据集的第一(第 0)行(元rows组列表,其中每个元组都是 Cassandra 中的一行)

from cassandra.util import OrderedMapSerializedKey

def pandas_factory(colnames, rows):

    # Convert tuple items of 'rows' into list (elements of tuples cannot be replaced)
    rows = [list(i) for i in rows]

    # Convert only 'OrderedMapSerializedKey' type list elements into dict
    for idx_row, i_row in enumerate(rows):

        for idx_value, i_value in enumerate(i_row):

            if type(i_value) is OrderedMapSerializedKey:

                rows[idx_row][idx_value] = dict(rows[idx_row][idx_value])

    return pd.DataFrame(rows, columns=colnames)
Run Code Online (Sandbox Code Playgroud)

您必须插入一些自动检查 Cassandra 映射字段之前/之后是否有最小一个值,或者相​​应地手动修改上述脚本。

美好的一天!