我目前连接到一个提供 Protocol Buffer 的服务器。我可能会收到大量消息。目前我读取 Protocol Buffer 并将它们转换为 Pandas DataFrame 的过程(通常不是必要的步骤,但 Pandas 提供了用于分析数据集的好工具)是:
- 读取protocol buffer,它将是一个google protobuf对象
- 使用 protobuf_to_dict 将 Protocol Buffer 转换为字典
- 使用
pandas.DataFrame.from_records
获取DataFrame
这很好用,但是考虑到我从 protobuf 读取的大量消息,转换为字典然后再转换为 pandas 的效率非常低。我的问题是:是否有可能制作一个可以使 python protobuf 对象看起来像字典的类?也就是说,删除步骤 2。任何引用或伪代码都会有所帮助。
最佳答案
您可能需要检查 ProtoText python 包。 它确实提供了类似 dict 的就地操作来访问您的 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
关于python - 从 Protocol Buffer 创建一个类似对象的 python 字典以用于 pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24682713/