【问题标题】:Convert a list of dicts to DataFrame and back to exactly same list?将字典列表转换为 DataFrame 并返回完全相同的列表?
【发布时间】:2020-03-08 05:40:10
【问题描述】:

在我的 Django 视图中,我想将字典列表加载到 Pandas 数据框中,对其进行操作,再次转​​储到 dict 并返回此类操作数据作为此视图 JSON 响应的一部分

def test(request):
    pre_pandas = [{'type': 'indoor', 'speed': 1, 'heart_rate': None}, {'type': 'outdoor', 'speed': 2, 'heart_rate': 124.0}, {'type': 'commute', 'speed': 3, 'heart_rate': 666.0}, {'type': 'indoor', 'speed': 4, 'heart_rate': 46.0}]

    df = pd.DataFrame(pre_pandas)

    # some data manipulation here...

    post_pandas = df.to_dict(orient='records')

    response = {
        'pre_pandas': pre_pandas,
        'post_pandas': post_pandas,
    }

    return JsonResponse(response)

我的方法的问题是 Pandas 的 to_dict() 方法将 Python 的 None 替换为 nan,因此响应中包含 NaN

 {"pre_pandas": [{"type": "indoor", "speed": 1, "heart_rate": null}...], "post_pandas": [{"heart_rate": NaN, "speed": 1,...}]

而 JavaScript 无法处理 NaN

有没有办法将数据帧转储到 dict,以便输出与构建它的 dict 完全相同?

我可以使用列表 replace() 方法手动调整数据,但感觉很尴尬,而且我需要涵盖所有其他(如果有的话)转换 Pandas 的 to_dict() 方法可能会做的事情。

我也无法将 post_pandas 转储到 JSON,因为我已经在 JsonResponse 中这样做了。

【问题讨论】:

    标签: python json django pandas dataframe


    【解决方案1】:

    您的 pre_pandas 数据框中的列是从提供的字典中推断出来的,为了防止这种情况,您可以显式指定数据类型对象。是什么强制所有值都为 object 类型。

    这样:

    df = pd.DataFrame(pre_pandas, dtype=object)
    

    【讨论】:

    • 感谢您的提示,但我无法将数值数据作为字符串读取,因为我实际上需要执行一些计算。
    • 这里的问题是“无”本身不是一个浮点对象表示。这就是为什么它被转换为 np.NaN 以符合 heart_rate 列的 dtype。否则,您最终会得到一个混合类型的列。为了克服这个问题,您可以使用允许该行为的自定义 dtype,或者将列转换为浮点数(通过转换为 Dataframe 隐式完成)并在之后重新格式化列(例如使用替换)。
    猜你喜欢
    • 2022-10-13
    • 2014-01-05
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    相关资源
    最近更新 更多