对Yelp dataset 中的数据进行json格式转csv操作

Yelp dataset原始数据集下载地址为:https://www.yelp.com/dataset/documentation/main
本人用到的两个数据集为yelp_photos.tar和yelp_dataset.tar,两个压缩包加一块大约10.3GB。
对Yelp dataset 中的数据进行json格式转csv操作_第1张图片
在GitHub上浏览基于yelp dataset数据集做的推荐系统项目时,发现人们用csv格式的数据集处理数据更加方便。而在GitHub上找到的json转csv的代码并不能达到理想转换效果,于是自己编写了jsontocsv_business.py和jsontocsv_review.py程序,此处贡献前者与大家交流学习。

import csv
import json
import sys
import os
import pandas as pd
import numpy as np
json_file_path='/home/yelp_dataset/business.json'
csv_file_path='/home/yelp_dataset/business.csv'
#打开business.json文件,取出第一行列名
with open(json_file_path,'r',encoding='utf-8') as fin:
    for line in fin:
        line_contents = json.loads(line)
        headers=line_contents.keys()
        break
    print(headers)
#将json读成字典,其键值写入business.csv的列名,再将json文件中的values逐行写入business.csv文件
with open(csv_file_path, 'w', newline='',encoding='utf-8') as fout:
    writer=csv.DictWriter(fout, headers)
    writer.writeheader()
    with open(json_file_path, 'r', encoding='utf-8') as fin:
        for line in fin:
            line_contents = json.loads(line)
            if 'Phoenix' in line_contents.values():
                writer.writerow(line_contents)
 # 删除state','postal_code','is_open','attributes'列,并保存
df_bus=pd.read_csv(csv_file_path)
df_reduced=df_bus.drop(['state','postal_code','is_open','attributes'], axis = 1)
df_cleaned=df_reduced.dropna()
df_cleaned.to_csv(csv_file_path,index=False)


df_bus=pd.read_csv(csv_file_path)
n=len(df_bus)
for i in range(n):
    k1 = str(df_bus.categories.loc[i]).split(',')
    if 'Restaurants' not in k1 and ' Restaurants' not in k1:
        df_bus.drop(index=i, inplace=True)

df_bus.to_csv(csv_file_path,index=False)

由于个人需要,在json转csv过程中删除了’state’,‘postal_code’,‘is_open’,'attributes’四列数据,仅留下city为Phoenix且含有Restaurants的行。
原始数据为131MB的business.json经处理后仅剩940KB,而review.json由于本身大小为4.97GB,不建议用将dataframe整体读出的方式对其进行处理,效率太慢,本人采用逐行读出写入的方式成功将review.json转换成csv格式,大小由4.97GB缩小到4.39GB,后续再根据自己的需要进行数据清洗。

你可能感兴趣的:(推荐系统)