用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"}
编写一个解析并统计学习数据的函数,统计user_id的总学习时间和学习次数。
用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)