关于拉格朗日插值法,参考:
数据集
加载我们的数据集
data_path = r'D:\OneDrive\python\datasets\python_data_analysis_and_mining_action-master\chapter4\data\catering_sale.xls'
df = pd.read_excel(data_path)

这个是每天的销量数据
缺失值
前面我们知道,对于缺失值的处理,我们可以使用插值法来填补数据
我们得先看看有多少缺失值
df.isna().sum()

这里只有1条缺失值数据
df[df['销量'].isna()]

拉格朗日插值法
我们找到缺失值了,下面就该调用函数使用了
先回顾一下,怎么使用,首先我们要知道变量X和变量Y
因为我们的缺失值是销量,所以变量Y就是已知的销量
X的话,可以是索引
前面提过,元素个数不要太多,因为这个scipy中的lagrange函数并不稳定
至于到底选取几个,我暂时没有什么概念,书中取的是10,我这里也取10吧,前面取5个,后面取5个,共10个值
df2 = df.query('9<=index<14 or 15<=index<19')['销量']

这里我其实有一个疑问,就是X的值如何取?
书中是使用的下标,也就是index的值
x = df2.index.values
y = df2.values

调用拉格朗日函数
rs = lagrange(x,y)
print(rs)

最后,看看我们的缺失值是多少呢?
rs(14)

这里得出来是3831,这个数据靠不靠谱呢?
先从我们的区间中看看:

3831看上去还可以,而且呢,因为我们还有一个日期字段,也可以结合星期看看
df['星期几'] = df['日期'].dt.weekday_name
df.query('星期几=="Saturday"')

好像也可以接受呢
最后呢,我们要回顾一下,我们都做了些什么,我们是一步一步处理的,但是实际情况下,我们不会手工的去看缺失值在哪里,我们需要用代码去筛选出缺失值,并且将最后的值插回数据集中,思考一下,如何自动化?
网友评论