[英]Create a Dataframe from list of Dictionaries
Please help me creating a Dataframe from list of dictionaries请帮我从字典列表中创建一个 Dataframe
Dataset = [{'A': ' X1'}, {'B': ' Y1'}, {'A': ' X2'}, {'B': ' Y2'}, {'A': ' X3'}, {'B': ' Y3'}, {'C': ' Z3'}]
The output should be: output 应该是:
you can use defaultdict and pandas' from_dict method.你可以使用defaultdict和 pandas 的from_dict方法。 The trick is to use the orient parameter and transpose the dataframe in order to handle the missing values in the C column
诀窍是使用 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.