【数据分析面试】22.补充缺失数据(Python:数据插值interpolate()用法)

在这里插入图片描述

题目

数据集来自一个气候研究组织,列表里带有不同城市每日温度读数的时间序列数据。该数据框有三列:datecitytemperature

由于数据记录问题,某些日期的温度读数可能丢失。该组织需要每天的温度读数,因此他们要求你用线性插值来估算缺失的数据。

编写一个使用 Pandas 的 Python 函数,使用 线性插值(linear interpolation) 来估算缺失的数据并填充数据框。

注释:

  • 在估算某个城市的缺失值时,插值应仅考虑来自同一城市的数据。
  • 温度记录问题很少发生,因此可以假设连续两天不会出现数据缺失。
  • 您还可以假设数据框中的第一个和最后一个日期都包含有效的温度数据。

示例:

输入:

datecitytemperature
2023-01-01London10
2023-01-02LondonNaN
2023-01-03London12
2023-01-04LondonNaN
2023-01-05London14
2023-01-01Berlin-2
2023-01-02Berlin-1
2023-01-03BerlinNaN
2023-01-04Berlin1
2023-01-05Berlin2

输出:

datecitytemperature
2023-01-01London10
2023-01-02London11
2023-01-03London12
2023-01-04London13
2023-01-05London14
2023-01-01Berlin-2
2023-01-02Berlin-1
2023-01-03Berlin0
2023-01-04Berlin1
2023-01-05Berlin2

答案

import pandas as pd

# 示例数据
data = pd.DataFrame({
    'date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05',
             '2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'],
    'city': ['London', 'London', 'London', 'London', 'London',
             'Berlin', 'Berlin', 'Berlin', 'Berlin', 'Berlin'],
    'temperature': [10, None, 12, None, 14, -2, -1, None, 1, 2]
})

def fill_missing_temperature(data):
    # 按城市分组
    grouped = data.groupby('city')
    
    # 用于存储填充后的数据
    filled_data = []
    
    # 对每个城市的数据进行插值
    for city, group in grouped:
        # 对温度列进行线性插值
        filled_group = group.interpolate(method='linear', limit_direction='both')
        filled_data.append(filled_group)
    
    # 合并填充后的数据
    filled_data = pd.concat(filled_data)
    
    return filled_data

# 填充缺失的温度数据
filled_data = fill_missing_temperature(data)

# 重新按照索引排序
filled_data.sort_index()

什么是线性插值?

线性插值是一种方法,用于在已知数据点之间的位置估算缺失值。它假设数据的变化是直线形式的。比如,如果你有两个点的数据,线性插值会用一条直线连接它们,然后根据这条直线上的位置来估算其他点的值。在时间序列数据中,线性插值通过已知时间点的数据来估算缺失时间点的数据,假设数据在时间上是线性变化的。

举个例子,假设我们有一条线上有两个点 A 和 B,它们的坐标分别是 (x1, y1) 和 (x2, y2)。线性插值会根据这两个点之间的直线来估算任意两个点之间的值。如果我们想要估算在 x1 和 x2 之间的某个点的 y 值,线性插值会沿着直线在 x1 和 x2 之间的对应位置计算出该点的 y 值。

interpolate 函数

interpolate 是 Pandas 提供的一个函数,用于数据插值,即根据已知数据点的值来估算缺失值。在 Pandas 中,interpolate 函数通常用于处理时间序列数据或其他连续数据,以填补缺失值。

基本用法:

interpolated_series = series.interpolate(method='linear')

这里,series 是一个 Pandas Series 对象,表示要进行插值处理的数据列。interpolate 方法会返回一个新的 Series 对象,其中缺失值已经通过插值算法填充。

常用参数:

  • method: 插值方法。常用的包括 'linear'(线性插值)、'nearest'(最近邻插值)、'spline'(样条插值)等。默认为 'linear'
  • limit: 指定连续缺失值插值的最大数量。默认为 None,表示可以插值所有缺失值。
  • limit_direction: 指定插值限制的方向,可以是 'forward'(向前)或 'backward'(向后)。默认为 None,表示双向限制。
  • inplace: 是否在原地修改数据,默认为 False,表示返回一个新的插值后的 Series。

更多详细答案可关注公众号查阅。
在这里插入图片描述

  • 37
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值