python - 从 Protocol Buffer 创建一个类似对象的 python 字典以用于 pandas

标签 python pandas protocol-buffers

我目前连接到一个提供 Protocol Buffer 的服务器。我可能会收到大量消息。目前我读取 Protocol Buffer 并将它们转换为 Pandas DataFrame 的过程(通常不是必要的步骤,但 Pandas 提供了用于分析数据集的好工具)是:

  1. 读取protocol buffer,它将是一个google protobuf对象
  2. 使用 protobuf_to_dict 将 Protocol Buffer 转换为字典
  3. 使用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/

相关文章:

python - 在 Pandas 图上标记事件点

pandas - Pandas 数据透视表只有列总计,没有行总计

python - 发送帖子请求python

javascript - 通过 Ajax 从 Django 连续获取图像

python - 将 MultiIndex DataFrame 格式从列排序到 Pandas 中的变量

python - 在 Pandas 中连续获取计数唯一值

java - Protoc Java 插件的依赖关系?

documentation - 有没有办法在 protobuf (proto2) 中创建类型别名?

go - 使用 protoc-gen-go 创建一个 .pb.go 导入 google/golang 但找不到包

python - 如何从键值对列表中删除值