请帮助我根据词典列表创建数据框
Dataset = [{'A': ' X1'}, {'B': ' Y1'}, {'A': ' X2'}, {'B': ' Y2'}, {'A': ' X3'}, {'B': ' Y3'}, {'C': ' Z3'}]
输出应为:
答案 0 :(得分:1)
您可以使用defaultdict和熊猫的from_dict方法。诀窍是使用orient参数并转置数据框以处理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)