[英]How to transform a List of a List of dicts into a Pandas Dataframe
I Have have an output from a web crawling and I don't know how to convert into a Pandas Dataframe.我有一个网络爬虫的输出,但我不知道如何转换为 Pandas 数据帧。
This is my output:这是我的输出:
[[{'galaxy s10': 1, 'galaxy m30': 1, 'iphone xs max': 1, 'one vision': 1, 'moto g7': 1}], [{'iphone 11': 3}], [], [], [{'iphone 11': 1}, {'iphone 11': 1}]]
I think this output is a list of a lists of dicts
.我认为这个输出是一个
dicts
列表的列表。
I would like to transform into a pandas dataframe, like this:我想转换成一个熊猫数据框,像这样:
enter image description here在此处输入图片说明
Thanks!谢谢!
I think this solves the problem.我认为这可以解决问题。
import pandas as pd
from itertools import chain
a_list = [[{'galaxy s10': 1, 'galaxy m30': 1, 'iphone xs max': 1, 'one vision': 1, 'moto g7': 1}],
[{'iphone 11': 3}], [], [], [{'iphone 11': 1}, {'iphone 11': 1}]]
consolidate = []
for l in list(chain(*a_list)):
temp = {}
for k,(key, value) in enumerate(l.items()) :
temp.update({f"Cellphone{k+1}":key,
f"Cellphone{k+1}_views":value})
consolidate.append(temp)
df = pd.DataFrame.from_dict(consolidate)
df
this part list(chain(*a_list ))
will transform the list of lists.这部分
list(chain(*a_list ))
将转换列表列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.