Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Please help me creating a Dataframe from list of dictionaries

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

The output should be:

The output should be:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
165 views
Welcome To Ask or Share your Answers For Others

1 Answer

you can use defaultdict and pandas' from_dict method. The trick is to use the orient parameter and transpose the dataframe in order to handle the missing values in the C column

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...