簡體   English   中英

將字典列表轉換為 DataFrame 並返回完全相同的列表?

[英]Convert a list of dicts to DataFrame and back to exactly same list?

In my Django view, I want to load a list of dictionaries into a Pandas dataframe, manipulate it, dump to dict again and return such manipulated data as a part of this view's JSON response:

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

有沒有辦法將 dataframe 轉儲到字典中,以便 output 與構建它的字典完全相同?

我可以使用 list replace()方法手動調整數據,但感覺很尷尬,而且我需要涵蓋所有其他 - 如果有的話 - Pandas 的to_dict()方法可能會做的轉換。

我也不post_pandas轉儲到 JSON,因為我已經在 J JsonResponse中這樣做了。

您的 pre_pandas Dataframe 中的列是從提供的字典中推斷出來的,為了防止這種情況,您可以顯式指定數據類型 object。 是什么強制所有值的類型為 object。

像那樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM