1. 将用户的json文件转换为表格形式
描述: 现有一个Nowcoder.json文件,它记录了牛客网的部分用户数据,包含如下字段(字段与字段之间以逗号间隔):
Nowcoder_ID:用户ID
Level:等级
Achievement_value:成就值
Graduate_year:毕业年份
Language:常用语言
如果你读入了这个json文件,能将其转换为pandas的DataFrame格式吗?
实现代码:
import pandas as pd
import json
pd.set_option('display.width', 300) # 设置字符显示宽度
pd.set_option('display.max_rows', None) # 设置显示最大行
pd.set_option('display.max_columns', None)
with open('Nowcoder.json', 'r') as f:
data = json.loads(f.read())
print(pd.DataFrame(data))
运行结果:
2. 牛客网的每日练题量
描述: 现有牛客网12月每天练习题目情况的数据集nowcoder.csv。包含如下字段(字段之间用逗号分隔):
user_id:用户id
question_id:问题编号
result:运行结果
date:练习日期
请你统计2021年12月每天练习题目的数量。
实现代码:
import pandas as pd
nowcoder = pd.read_csv('nowcoder.csv', parse_dates=True, index_col='date')
nowcoder.index = nowcoder.index.map(lambda x: x.strftime('%Y-%m-%d'))
date_group = nowcoder.groupby('date')['question_id'].count()
print(date_group)
运行结果:
3. 牛客网用户练习的平均次日留存率
描述: 现有牛客网12月每天练习题目情况的数据集nowcoder.csv。包含如下字段(字段之间用逗号分隔):
user_id:用户id
question_id:问题编号
result:运行结果
date:练习日期
现需要查看用户在某天练习后第二天还会再来练习的留存情况,请计算用户练习的平均次日留存率。
实现代码:
# 不走笛卡尔积
import pandas as pd
from datetime import timedelta, datetime
nowcoder = pd.read_csv("nowcoder.csv")
nowcoder["date"] = pd.to_datetime(nowcoder["date"]).dt.date
# 日期+1
nowcoder["datenew"] = nowcoder["date"].apply(lambda x: x + timedelta(days=1))
# join交集
nowcoder_1 = pd.merge(
nowcoder[["user_id", "date"]],
nowcoder[["user_id", "datenew"]],
left_on=["user_id", "date"],
right_on=["user_id", "datenew"],
)
# 次日留存
cnt = nowcoder_1.shape[0] / nowcoder.shape[0]
print(round(cnt, 2))
运行结果:
4. 牛客网每日正确与错误的答题次数
描述: 现有牛客网12月每天练习题目的数据集nowcoder.csv。包含如下字段(字段之间用逗号分隔):
user_id:用户id
question_id:问题编号
result:运行结果
date:练习日期
请你统计2021年12月答题结果正确和错误的前提下每天的答题次数。
实现代码:
import pandas as pd
import datetime
nowcoder = pd.read_csv('nowcoder.csv')
nowcoder['year-month-day'] = pd.to_datetime(nowcoder['date']).dt.date
nowcoder_1 = nowcoder.groupby(by=['result', 'year-month-day'])['year-month-day'].count()
print(nowcoder_1)
运行结果: