我在 Cassandra 中有一列由列表映射组成,当使用 Python 驱动程序查询时,它返回一个 OrderedMapSerializedKey 结构。该结构是列表的映射。我想将整个查询放入 pandas 中。
要从 OrderedMapSerializedKey 结构中提取数据,即获取键并将其用作新列的标签,并仅保留列表的第一个元素作为值,我使用上述方法here在返回构建的 DataFrame 之前,在工厂中进行一些复杂/肮脏的操作。
有人问了类似的问题here,没有真正的答案。
有没有更好的方法将这样的 OrderedMapSerializedKey 结构转换为可以轻松加载到 pandas DataFrame 中的 Python 字典?
我认为最终的解决方案可能是存储OrderedMapSerializedKey
Cassandra 结构作为dict
在您的数据框列中,您可以将此值/列传输给您想要的任何人。最终是因为您可能不知道 Cassandra 行中的实际键(可能将不同的键插入到行中)。
所以这里是我测试过的解决方案,你只需要改进pandas_factory功能:
EDIT:
在之前的解决方案中,我仅替换了 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)
您必须插入一些自动检查 Cassandra 映射字段之前/之后是否有最小一个值,或者相应地手动修改上述脚本。
美好的一天!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)