【问题标题】:How do i parse a json string in a csv column and break it down into multiple columns?如何解析 csv 列中的 json 字符串并将其分解为多个列?
【发布时间】:2020-09-15 11:44:10
【问题描述】:

我的目标是读取位于 csv 文件的第 4 列“REQUEST_RE”中的 json 字符串,并将该第 4 列分解为单独的列。

我的数据在第 4 列的每个 csv 行的格式如下:

第 2 行:{"Fruit":"Apple","Cost":"1.5","Attributes":{"ID":"001","Country":"America"}}

第 3 行:{"Fruit":"Orange","Cost":"2.0","Attributes":{"ID":"002","Country":"China"}}

改成:

我正在尝试这个: Parsing a JSON string which was loaded from a CSV using Pandas

我最终使用了这个:

InterimReport = pd.read_csv(filename, index_col=False, usecols=lambda col: col not in ["SYSTEMID"]) InterimReport.join(InterimReport['REQUEST_RE'].apply(json.loads).apply(pd.Series))

但我无法将我的 json 字符串拆分为列。

我的 json 字符串仍然是一个 json 字符串并且没有改变。

【问题讨论】:

  • json 是 Python 中的核心模块,也许你应该使用它?显示完整文件的前几行,而不仅仅是一列,还有读取它的代码。
  • 您收到了什么错误/究竟什么没有工作?

标签: python json parsing


【解决方案1】:

此时您应该忽略 JSON 字符串来加载 CSV 文件。

然后将列转换为 json 列表并对其进行规范化:

tmp = pd.json_normalize(InterimReport['REQUEST_RE'].apply(json.loads).tolist()).rename(
          columns=lambda x: x.replace('Attributes.', ''))

你应该得到类似的东西:

    Fruit Cost   ID  Country
0   Apple  1.5  001  America
1  Orange  2.0  002    China

您可以轻松地连接到原始数据框:

InterimReport = pd.concat([InterimReport.drop(columns=['REQUEST_RE']), tmp], axis=1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 2020-03-28
    相关资源
    最近更新 更多