【问题标题】:Issue while converting API output to Pandas Dataframe将 API 输出转换为 Pandas Dataframe 时出现问题
【发布时间】:2019-11-14 14:24:58
【问题描述】:

我有以下格式的 API 输出。

reponse.text

'{"position": {"lat": 1.352083, "lon": 103.819836}, "mapView": {"N": 1.4784001, "E": 104.0945001, "S": 1.1496, "W": 103.594}}\n'

我想将此输出转换为 pandas 数据帧。

我的代码

import json
d = json.loads(response.text)
df = pd.DataFrame(d)

电流输出

    position    mapView
E   NaN            104.0945
N   NaN             1.4784
S   NaN             1.1496
W   NaN            103.5940
lat 1.352083        NaN
lon 103.819836      NaN

我的预期输出

lat       lon
1.352083  103.819836 

这在python中如何实现?

【问题讨论】:

    标签: python json python-3.x pandas dataframe


    【解决方案1】:

    你很亲密。 import json_normalize from pandas 然后你就可以简单地使用了

    from pandas.io.json import json_normalize
    
    jsonData = json.loads(response.text)
    
    df = json_normalize(jsonData)
    

    打印(df)

    position.lat  position.lon  mapView.N  mapView.E  mapView.S  mapView.W
        1.352083    103.819836     1.4784   104.0945     1.1496    103.594
    

    然后只需删除多余的列并正确重命名即可。

    【讨论】:

      【解决方案2】:
      import pandas as pd
      import json
      d = json.loads(response.text)
      
      df =pd.DataFrame([d['position']])
      

      【讨论】:

        【解决方案3】:

        您将 json 解析器创建的整个字典作为参数传递,而您只想使用位置键。

        请查看 DataFrame 构造函数文档页面here 以获取其他参数。

        >>> import pandas as pd
        >>> import json
        >>> api_resp = json.loads('{"position": {"lat": 1.352083, "lon": 103.819836}, "mapView": {"N": 1.4784001, "E": 104.0945001, "S": 1.1496, "W": 103.594}}\n')
        >>> api_resp
        {'position': {'lat': 1.352083, 'lon': 103.819836}, 'mapView': {'N': 1.4784001, 'E': 104.0945001, 'S': 1.1496, 'W': 103.594}}
        >>> df = pd.DataFrame(data=api_resp['position'], index=[0])
        >>> df
                lat         lon
        0  1.352083  103.819836
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-05-09
          • 2020-03-29
          • 2018-05-23
          • 1970-01-01
          • 2021-02-05
          • 1970-01-01
          • 2017-04-27
          相关资源
          最近更新 更多