在这里插入图片描述

题目

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

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

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

注释:

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

示例:

输入:

date city temperature
2023-01-01 London 10
2023-01-02 London NaN
2023-01-03 London 12
2023-01-04 London NaN
2023-01-05 London 14
2023-01-01 Berlin -2
2023-01-02 Berlin -1
2023-01-03 Berlin NaN
2023-01-04 Berlin 1
2023-01-05 Berlin 2

输出:

date city temperature
2023-01-01 London 10
2023-01-02 London 11
2023-01-03 London 12
2023-01-04 London 13
2023-01-05 London 14
2023-01-01 Berlin -2
2023-01-02 Berlin -1
2023-01-03 Berlin 0
2023-01-04 Berlin 1
2023-01-05 Berlin 2

答案

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。

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

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐