【问题标题】:How to convert an object with dict shape in a dict or DataFrame (Python)如何在 dict 或 DataFrame (Python) 中转换具有 dict 形状的对象
【发布时间】:2019-11-21 08:35:59
【问题描述】:

我正在使用两个 IMU,以获得角度。情况是,当我收到数据时,它的格式如下:

{heading : 0.002, pitch : 0.000, roll : -0.000, yaw : 0.000}

在这种格式中,键值不是字符串,它只是一个对象。为此,当我有一些此类对象时,如果我将所有这些对象制作一个列表,然后从列表中制作一个 DataFrame,结果是

                          0
0    {heading : 0.002, pitch : 0.000, roll : 0.000,...
1    {heading : 0.002, pitch : 0.000, roll : 0.000,...
2    {heading : 0.000, pitch : 0.000, roll : 0.000,...
3    {heading : 0.002, pitch : 0.000, roll : 0.000,...
4    {heading : 0.002, pitch : 0.000, roll : 0.000,...
..                                                 ...
129  {heading : 0.002, pitch : 0.000, roll : 0.000,...
130  {heading : 0.002, pitch : 0.000, roll : 0.000,...
131  {heading : 0.002, pitch : 0.000, roll : 0.000,...
132  {heading : 0.002, pitch : 0.000, roll : 0.000,...
133  {heading : 0.002, pitch : 0.000, roll : 0.000,...

我想得到这样的东西:

    heading    pitch     roll   yaw
0    value     value     value  value
1    value     value     value  value
2    value     value     value  value

有人可以帮助我吗?谢谢!

【问题讨论】:

  • 问题本身并不清楚,因为您创建了某种字典结构,其中的键值无效,既不是字符串也不是对象,因为您没有提供有关如何创建这些对象的任何信息。因此,目前还不清楚您是否可以从您提供的这个伪 dict 结构中创建一个字符串。
  • 我建议您应该强制为您提供此类伪 dict 的输出将有效的键值作为字符串并为您提供 json 格式的数据。

标签: python dataframe dictionary


【解决方案1】:

您可以使用hjson 模块

import hjson
data = ['{heading : 0.002, pitch : 0.000, roll : -0.000, yaw : 0.000}',
        '{heading : 0.001, pitch : 0.003, roll : -0.000, yaw : 0.005}']
new_data = [hjson.loads(d) for d in data]
import pandas as pd
pd.DataFrame(new_data)


    heading     pitch   roll    yaw
0   0.002       0.000   0       0.000
1   0.001       0.003   0       0.005

【讨论】:

  • 谢谢,我去测试一下
  • Python 本身也有 json 内置模块,不需要 pip install: json.load
【解决方案2】:

Pandas 有一个pd.read_json 方法。

来自文档:

>>> df.to_json(orient='records')
'[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
>>> pd.read_json(_, orient='records')
  col 1 col 2
0     a     b
1     c     d

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 2018-10-14
    • 2020-10-23
    • 2016-05-18
    • 2021-11-06
    • 2018-01-08
    • 1970-01-01
    相关资源
    最近更新 更多