【问题标题】:How to read data from json file and convert it to csv using pandas?如何从 json 文件中读取数据并使用 pandas 将其转换为 csv?
【发布时间】:2017-06-10 09:20:44
【问题描述】:

我正在从事一个数据挖掘项目。我需要从属于亚马逊的 json 格式数据集中读取数据。
数据集格式如下:
首先我想提取这些行:
[产品名称]、[评级]
之后,我想将行写入一个 csv 文件,其中包含名为 productName 和 Rating 的两列。有没有办法通过使用 pandas 库来实现这一点?

【问题讨论】:

  • 您可以将json 的示例添加为文本吗?
  • 同时检查 json 是否有效 - jsonlint.com
  • 这肯定是一个很好的帮助,但它并不能完全回答这个问题,特别是对于我们需要提取行的部分。无论如何感谢您的帮助。

标签: python json csv pandas


【解决方案1】:

我已将数据子集转换为 DF。请注意,您拥有的数据不是 json 格式的数据。

import pandas as pd
import json 
from collections import defaultdict
import re

f=open('inv.json')
text= f.readlines()
RowID=[]
result={}

for item in text:
    if item.startswith("###"):
        RowID=re.findall('\d+', item)
        result[RowID[0]]={}
    elif ":" in item:
        key,value =item.split(":",1)
        result[RowID[0]][key.strip()]=value.strip()
df= pd.DataFrame(result)
print df.transpose()

样本输入

    #####1
[ID]:0
[ProductId]:0
[rating]:2.0

#####2
[ID]:1
[ProductId]:2
[rating]:3.0
[fullText]:It is a good
[weburl]:http://example.org:xx

输出

       [ID] [ProductId]    [fullText] [rating]           [weburl]
1    0           0           NaN      2.0                NaN
2    1           2  It is a good      3.0  http://example.org:xx

【讨论】:

  • 我试过你开发的代码。不幸的是,它给出了一个错误。文件“C:\Users\masoud\Desktop\Dataset\data3\aa - Copy.py”,第 16 行,在 key,value =item.split(":") ValueError: too many values to unpack (expected 2)
  • 更新了答案,即我们期望 OP 具​​有最低工作输入和预期输出的原因。
猜你喜欢
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 2014-11-23
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多