用Pandas讀取json文件,截取其中一段json文件如下圖:
{"minutes": 30, "created_at": "2016-05-01 00:00:10", "user_id": 199071,
"lab": "\u7528\u6237\u53ca\u6587\u4ef6\u6743\u9650\u7ba1\u7406",
"course": "Linux \u57fa\u7840\u5165\u95e8\uff08\u65b0\u7248\uff09"}
編寫一個(gè)解析并統(tǒng)計(jì)學(xué)習(xí)數(shù)據(jù)的函數(shù)邻遏,統(tǒng)計(jì)user_id的總學(xué)習(xí)時(shí)間和學(xué)習(xí)次數(shù)。
用pandas.read_json讀取json文件,代碼如下:
import pandas as pd
def analysis(file, user_id):
with open(file, 'r') as f:
if not f:
return 0
df = pd.read_json(f, orient='records')
dfs = df[df['user_id'] == user_id]
times = dfs.shape[0]
minutes = dfs['minutes'].sum()
return times, minutes
if __name__ == '__main__':
result = analysis('user_study.json', 199071)
print(result)