简体   繁体   English

CSV中的字典列表

[英]List of Dicts in CSV

I have a CSV document which has a column where each cell contains a list of dicts. 我有一个CSV文档,其中包含一列,其中每个单元格包含字典列表。 Any advice on how to extract that data while keeping it as lists of dicts would be appreciated. 任何有关如何提取数据同时将其保留为字典列表的建议都将受到赞赏。 I've tried the usual json/pandas/csv read-ins and none of them seem to work properly (converts to strings/unicode, which isn't surprising but is still frustrating). 我已经尝试了通常的json / pandas / csv读入,但它们似乎都无法正常工作(转换为字符串/ unicode,这并不奇怪,但仍然令人沮丧)。 Ultimately, I'd like the output to be a dataframe, where the header row is the keys and each following row is the data. 最终,我希望输出是一个数据框,其中标题行是键,随后的每一行是数据。

Sample CSV Section: 样本CSV部分:

1    results

2    [{"y": 47, "type": "square"}, {"type": "square", "b": 49}, {"type": "square", "z": 29}, {"a": 69, "type": "square"}, {"type": "square", "x": 81}]

3    [{"type": "circle", "b": 90}, {"y": 12, "type": "circle"}, {"a": 78, "type": "circle"}, {"type": "circle", "c": 74}, {"type": "circle", "x": 14}, {"type": "circle", "z": 19}]

4    [{"type": "square", "b": 85}, {"type": "square", "x": 73}, {"type": "square", "c": 50}]

5    [{"type": "triangle", "c": 71}, {"type": "triangle", "z": 66}, {"type": "triangle", "x": 16}, {"type": "triangle", "b": 38}, {"y": 67, "type": "triangle"}, {"a": 80, "type": "triangle"}]

Sample Output: 样本输出:

  type      a   b   c   x   y   z
0 square    69  49  NaN 81  47  29
1 circle    78  90  74  14  12  19
2 square    NaN 85  50  73  NaN NaN
3 triangle  80  38  71  16  67  66

Evaluating each line in the file and doing some dictionary work gets you the desired result: 评估文件中的每一行并进行一些词典工作即可获得所需的结果:

with open(filename) as fobj:
    next(fobj)  # skip first line with word `results`
    data = [eval(line) for line in fobj if line.strip()]
res = []
for entry in data:
    d = entry[0].copy()
    for x in entry[1:]:
        d.update(x)
    res.append(d)
df = pd.DataFrame(res)
df.reindex_axis(['type', 'a', 'b', 'c', 'x', 'y', 'z'], axis=1)
df

在此处输入图片说明

If you unwanted text on these line. 如果您在这些行上不需要文本。 You can remove everything out side the [] : 您可以删除[]

eval('[' + line.split('[')[-1].split(']')[0] + ']')

Alternatively, you can use a regular expression: 另外,您可以使用正则表达式:

import re

eval(re.findall(r'\[.*?\]', line)[0])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM