从协议缓冲区创建一个类似python的字典,用于pandas

Jus*_*tin 6 python protocol-buffers pandas

我目前接口到提供协议缓冲区的服务器.我可能会收到大量的邮件.目前我的过程是读取协议缓冲区并将它们转换为Pandas DataFrame(一般不是必要的步骤,但Pandas提供了分析数据集的好工具):

  1. 读取协议缓冲区,它将是一个谷歌protobuf对象
  2. 使用protobuf_to_dict将协议缓冲区转换为字典
  3. 用于pandas.DataFrame.from_records获取DataFrame

这很好用,但是,鉴于我从protobuf中读取的大量消息,转换为字典然后转换为pandas是非常低效的.我的问题是:是否有可能创建一个可以使python protobuf对象看起来像字典的类?也就是说,删除步骤2.任何引用或伪代码都会有所帮助.

小智 4

您可能想检查ProtoText python 包。它确实提供了类似字典的就地操作来访问 protobuf 对象。

用法示例:假设您有一个 python protobuf 对象person_obj

import ProtoText
print person_obj['name']       # print out the person_obj.name 
person_obj['name'] = 'David'   # set the attribute 'name' to 'David'
# again set the attribute 'name' to 'David' but in batch mode
person_obj.update({'name': 'David'})
print ('name' in person_obj)  # print whether the 'name' attribute is set in person_obj 
# the 'in' operator is better than the google implementation HasField function 
# in the sense that it won't raise Exception even if the field is not defined  
Run Code Online (Sandbox Code Playgroud)