【问题标题】:Import CSV with nested JSON into Pandas DataFrame将带有嵌套 JSON 的 CSV 导入 Pandas DataFrame
【发布时间】:2018-08-14 19:12:46
【问题描述】:

我正在尝试使用 Jupiter Notebook 导入一个包含两个嵌套 JSON 对象的 csv 文件。

我收到了这个错误。

ParserError:标记数据时出错。 C 错误:预计第 3 行中有 29 个字段,看到 35

问题在于 Pandas 无法识别 JSON 对象,而只使用逗号分隔的 CSV 分隔符。

这是 CSV 文件的示例行:

309,DVD10_Welt.mxf,16947519284,00:37:32:24,0_yd3ugljx,"{"Type":"Source","Content-Type":"Beitrag"}",97,"Welt",NULL,NULL,NULL,"{"ContentType":"Beitrag","Description":"Sie beobachten jeden.","Keywords":["wissensthek","zukunft","\u00dcberwachung","roboter","technik","internet","dvd","wissen"],"ProductionDate":"2013-07-10T00:30:06.000Z","TitleIntern":null}"

这是我在 Jupyter 中的线路:

df = pd.read_csv(csv_file)
df

有人可以给我一个提示吗?

谢谢曼努埃尔

【问题讨论】:

    标签: json python-3.x pandas csv import


    【解决方案1】:

    我认为如果不进行预处理就无法阅读它,因为它不是有效的 CSV 文件。

    如果您可以保存正确引用的 CSV 文件 - 它会起作用。

    演示:

    In [87]: df = pd.DataFrame({'ID':[1,2]})
    
    In [88]: df['JSON'] = '{"Type":"Source","Content-Type":"Beitrag"}'
    
    In [89]: df
    Out[89]:
       ID                                        JSON
    0   1  {"Type":"Source","Content-Type":"Beitrag"}
    1   2  {"Type":"Source","Content-Type":"Beitrag"}
    
    In [90]: df.to_csv('d:/temp/a.csv', index=False)
    

    生成的 CSV:

    ID,JSON
    1,"{""Type"":""Source"",""Content-Type"":""Beitrag""}"
    2,"{""Type"":""Source"",""Content-Type"":""Beitrag""}"
    

    检查:

    In [91]: pd.read_csv('d:/temp/a.csv')
    Out[91]:
       ID                                        JSON
    0   1  {"Type":"Source","Content-Type":"Beitrag"}
    1   2  {"Type":"Source","Content-Type":"Beitrag"}
    

    【讨论】:

    • 感谢您的快速回复。我很感激。您是否有机会在 Python 中完成此预处理,是否必须手动完成?
    • @Manuel,您可以尝试在 Python 中执行此操作,但它不适用于一般情况,并且此代码可能随时中断...我会尝试正确保存 CSV 文件...
    • @Manuel,如果您认为 @Manuel 回答了您的问题,请考虑 accepting / upvoting 一个答案
    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2020-02-18
    • 2020-03-12
    • 2019-06-09
    • 2014-06-27
    相关资源
    最近更新 更多