[英]python list of dicts to dataframe
我有一个字典对象{key,value}
的列表,如下所示:
recd = [{'Type': 'status'}, {'Origin': 'I just earned the Rookie badge on #Yelp!'},
{'Text': 'I just earned the Rookie badge on'}, {'URL': ''},
{'ID': '95314179338158080'}, {'Time': 'Sun Jul 24 21:07:25 CDT 2011'},
{'RetCount': '0'}, {'Favorite': 'false'},
{'MentionedEntities': ''}, {'Hashtags': 'Yelp'}]
我尝试了多种方法将其移动到pandas数据框对象,其中键是列名,值是记录值。
s = pd.Series(data=recd) ## try #1
tweets = tweets.append(s, ignore_index=True)
tweets = tweets.append(recd, ignore_index=True) #try #2
tweets.from_items(recd) #try #3
mylist = [item.split(',') for item in recd] #try #4 (stack overflow)
tdf = pd.DataFrame(mylist)
tweets.from_records(recd) #try #5
tweets.concat(recd, axis=1, etc) # tries 6-20
当然,这些都不起作用。 在这一点上,我尝试了显而易见的方法,并使用了所有各种columns=
, ignore_index
等参数),我缺少了显而易见的方法。 我通常使用结构化数据转储,所以这对我来说是新的。 我怀疑我没有正确格式化数据,但是解决方案使我难以理解。
背景:我正在一次将一个非标准格式的大型已解析数据文件中的每个recd对象一次构建为一个完整的记录,然后尝试将其转换为pandas数据框,在其中可以将其保存为任意数量的可用格式。 该过程还消除了许多数据错误。 执行此操作的代码是:
k = line.split(":",1)
key = str(k[0].strip())
val = str(k[1].strip())
if key in TweetFields:
d = {key : val} # also tried d = [key:val]
recd.append(d)
谢谢你的建议。
您可以使用dict理解将dict列表合并为一个dict。 然后将该字典传递给pd.DataFrame
:
In [105]: pd.DataFrame({key: [val] for dct in recd for key, val in dct.items()})
Out[105]:
Favorite Hashtags ID MentionedEntities \
0 false Yelp 95314179338158080
Origin RetCount \
0 I just earned the Rookie badge on #Yelp! 0
Text Time Type URL
0 I just earned the Rookie badge on Sun Jul 24 21:07:25 CDT 2011 status
虽然这解决了转换类型的字典列表转换成数据帧的单排的问题,这将是preferrable避免使用类型的字典列表,因为建设为每行一个新的数据帧是低效的。
如果您解释原始数据的外观(具有多于一行的数据)以及最终的DataFrame的外观,则可能会得到更有用的答案。
如果只想转换1个字典列表:
temp_df = pd.DataFrame([{key: value for dict in recd for key, value in dict.items()}])
但是,如果您打算使用这种构造来创建具有许多行的DF,则应将每条记录的1个字典中的所有{key:values}连接起来,并将它们附加到列表中:
recd = [{'Type': 'status', 'Origin': 'I just earned the Rookie badge on #Yelp!',
'Text': 'I just earned the Rookie badge on', 'URL': '',
'ID': '95314179338158080', 'Time': 'Sun Jul 24 21:07:25 CDT 2011',
'RetCount': '0', 'Favorite': 'false',
'MentionedEntities': '', 'Hashtags': 'Yelp'}]
recd.append({'Type': 'status', 'Origin': 'BLAH BLAH',
'Text': 'One more on the road', 'URL': '',
'ID': 'NA', 'Time': 'NA',
'RetCount': 'NA', 'Favorite': 'false',
'MentionedEntities': '', 'Hashtags': 'Yelp'})
temp_df = pd.DataFrame(recd)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.