簡體   English   中英

從字典列表創建 Dataframe

[英]Create a Dataframe from list of Dictionaries

請幫我從字典列表中創建一個 Dataframe

Dataset = [{'A': ' X1'}, {'B': ' Y1'}, {'A': ' X2'}, {'B': ' Y2'}, {'A': ' X3'}, {'B': ' Y3'}, {'C': ' Z3'}]

output 應該是:

輸出應該是:

你可以使用defaultdict和 pandas 的from_dict方法。 訣竅是使用 orient 參數並轉置 dataframe 以處理 C 列中的缺失值

def cast_to_dataframe(_ds):
    """
    Cast the given list of dictionaries to one dataframe

    :param _ds: List of dictionaries
    :return: DataFrame
    """

    final_dict = defaultdict(list)

    # Iterate through each dictionary in _ds
    for d in _ds:
        for key, value in d.items():
            final_dict[key].append(value)
    # Cast back to dict
    final_dict = dict(final_dict)
    df = pd.DataFrame.from_dict(final_dict, orient='index')

    return df.transpose()

dataset = [{'A': ' X1'}, {'B': ' Y1'}, {'A': ' X2'}, {'B': ' Y2'}, {'A': ' X3'}, {'B': ' Y3'}, {'C': ' Z3'}]

cast_to_dataframe(dataset)

暫無
暫無

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

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