Pandas:一种很好的时间序列模型滑窗技巧

一、前言

最近在玩一个时间序列的竞赛,里面有个大佬分享了他的源码,里面有一块滑窗的操作很厉害,我之前要么使用For循环来遍历,要么使用Pandas自带的shift+For循环,但是大佬的滑窗技巧是先对一些关键字段(比如人名、地名、物品型号)等进行编码,然后做一个组合编码,再通过-1、-2等操作获得前一天、两天的编码序号,最后通过Map的方式来匹配,效率那是相当的高。
我做了一下实验,同样的一些数据,如果用For循环大概要5分钟,shift+For大概要1分钟,而用大佬的滑窗技巧则只要1秒钟,差距啊~~
具体代码实现过程如下,具体数据可以参考我之前的帖子**《数据挖掘:智慧教育初赛相关思路和代码》**

二、代码

1、一开始仍然是常规的导入数据

import pandas as pd
import numpy as np
import os

pd.set_option('display.max_columns', None) #显示所有列
train_path = os.path.abspath('.') + '\\train_s1' + '\\'
test_path = os.path.abspath('.') + '\\test_s1' + '\\'

all_knowledge = pd.read_csv(train_path + 'all_knowledge.csv') #(2236, 5)
course = pd.read_csv(train_path + 'course.csv') #(8, 2)
exam_score = pd.read_csv(train_path + 'exam_score.csv') #(304500, 4)
student = pd.read_csv(train_path + 'student.csv') #(500, 2)
submission_s2 = pd.read_csv(test_path + 'submission_s1.csv') #(4000, 4)
course_list = ['course1', 'course2', 'course3', 'course4', 'course5', 'course6', 'course7', 'course8']

2、获得每门考试的次序

#获得每门考试的次序
total_course_exams = pd.DataFrame(columns=['exam_id', 'exam_count'])
for course in course_list:
    temp_course_exams = pd.read_csv(train_path + course + '_exams.csv')
    temp_course_exams = temp_course_exams[['exam_id']].reset_index()
    temp_course_exams['index'] = temp_course_exams['index'] + 1
    temp_course_exams = temp_course_exams.rename(columns={'index': 'exam_count'})
    total_course_exams = pd.concat([total_course_exams, temp_course_exams], axis=0, sort=False)
total_course_exams.head()

3、通过滑窗操作获得上一次考试的成绩

total_data = pd.concat([exam_score, submission_s2],axis=0, sort=False)
total_data.rename(columns={'pred': 'pre_score'}, inplace=True)
total_data = total_data.merge(total_course_exams, how='left', on='exam_id')
total_data['course_id'] = total_data['course'].map({'course1': 1, 'course2': 2, 'course3': 3,'course4': 4, 'course5': 5, 'course6': 6, 'course7': 7, 'course8': 8})
total_data['this_exam_student_id'] = total_data['student_id'] * 1000 + total_data['course_id'] * 100 + total_data['exam_count']
total_data['last_exam_student_id'] = total_data['student_id'] * 1000 + total_data['course_id'] * 100 + total_data['exam_count'] - 1

df_last = total_data[~total_data['score'].isnull()].set_index('this_exam_student_id')
total_data['pre_score'] = total_data['last_exam_student_id'].map(df_last['score'])
total_data = total_data.sort_values(by=['student_id', 'course', 'exam_count'])
total_data

结果如下图所示:
在这里插入图片描述

发布了90 篇原创文章 · 获赞 106 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_42029733/article/details/101756096