数据科学测试 3:使用Pandas进行测试

单元测试示例 - 混合层深度

图表显示了2010年5月在大西洋北部由一个ARGO浮标测量的温度剖面。该剖面在接近表面的区域有一个相对均匀的温度区域,这个区域被称为混合层。我们想要一个函数来找出这个层底部的深度。

我们将混合层深度定义为第一个深度,其温度比近表面温度低0.1度。我们定义近表面温度为顶部两个测量值的平均值。

定义我们的第一个一维数据函数

我们定义第一个函数。这个函数接受一个一维的温度值数组和一个浮点数来设置温度差异阈值。它会在整个温度剖面中进行简单的循环,直到找到第一个温度差异超过阈值的索引。

python 复制代码
def findMixedLayerIndex(temperature:np.ndarray,thresholdTemperatureDifference:float):

    surfaceTemps = temperature[:2].mean()

    depthIndex = 2

    temperatureDifference = surfaceTemps - temperature[depthIndex]

    while temperatureDifference < thresholdTemperatureDifference:

        depthIndex += 1

        temperatureDifference = surfaceTemps - temperature[depthIndex]

    return depthIndex

我们现在想用一些数据来测试这个函数。我们将手动定义温度数组。

python 复制代码
temperature = np.array([5.0,5.0,4.95,4.89,4.85])targetDepthIndex = 3output = mixedLayerIndex(temperature=temperature,thresholdTemperatureDifference=0.1)assert output == targetDepthIndex,f"output:{output},targetDepthIndex:{targetDepthIndex}"

太好了,这成功了!

我们在这里使用了Python的assert语句来测试输出是否正确。这在处理标量值或文本时是没问题的,但不适用于某些科学用例,例如:

  1. · 如果输出是一个数组,因为这会非常慢
  2. · 如果我们关心在某个容差范围内的相似性

定义我们的第二个用于二维数据的函数

相反,我们使用Numpy的内置测试模块np.testing。我们通过修改我们的混合层深度索引函数来展示这一点,使其能够处理二维数组而不是一维数组。

python 复制代码
def mixedLayerIndexArray(temperature:np.ndarray,thresholdTemperatureDifference:float):

    surfaceTemps = temperature[:2].mean(axis=0)

    depthIndexList = []

    for col in range(temperature.shape[1]):

        depthIndex = 2

        temperatureDifference = surfaceTemps[col] - temperature[depthIndex,col]

        while (temperatureDifference < thresholdTemperatureDifference) and (depthIndex < temperature.shape[0]-1):

            depthIndex += 1

            temperatureDifference = surfaceTemps[col] - temperature[depthIndex,col]

        depthIndexList.append(depthIndex)

    depthIndexArray = np.array(depthIndexList)

    return depthIndexArray
python 复制代码
temperature = np.array([

    [5.0,5.0,4.95,4.89,4.85],

    [5.0,5.0,4.95,4.94,4.93]]).Tprint(f"Shape of temperature array: {temperature.shape}")assert temperature.shape[1] == 2targetDepthIndexArray = np.array([3,4])output = mixedLayerIndexArray(temperature=temperature,thresholdTemperatureDifference=0.1)np.testing.assert_array_equal(output,targetDepthIndexArray)

Numpy的测试模块还允许您使用np.testing.assert_array_almost_equal来测试两个数组在指定的容差范围内是否几乎相等。

使用数据框进行测试

使用数据框进行测试与使用numpy进行测试类似。Pandas自带有其自己的测试模块,位于pd.testing。

python 复制代码
def mixedLayerIndexDataframe(temperatureDf:pd.DataFrame,thresholdTemperatureDifference:float):

    surfaceTemps = temperatureDf.iloc[:2].mean(axis=0)

    depthIndexList = []

    baseMixedLayerTemperature = []

    for col in temperatureDf.columns:

        depthIndex = 2

        temperatureDifference = surfaceTemps.iloc[col] - temperatureDf.iloc[depthIndex].loc[col]

        while (temperatureDifference < thresholdTemperatureDifference) and (depthIndex < temperature.shape[0]-1):

            depthIndex += 1

            temperatureDifference = surfaceTemps.iloc[col] - temperatureDf.iloc[depthIndex].loc[col]

        depthIndexList.append(depthIndex)

        baseMixedLayerTemperature.append(temperatureDf.iloc[depthIndex].loc[col])



    mixedLayerDf = pd.DataFrame({'depthIndex': depthIndexList,'mlTemp':baseMixedLayerTemperature})

    return mixedLayerDf

往期热门文章:

从 Pandas 到 Polars 二十六:在Polars中,不要遍历列

从 Pandas 到 Polars 二十三:如果你的数据已经排序,Polars可以为你提供助力

从 Pandas 到 Polars 十八:数据科学 2025,对未来几年内数据科学领域发展的预测或展望

从 Pandas 到 Polars 十三:流式处理的关键参数

从 Pandas 到 Polars 十:"Polars 表达式"是什么?

从 Pandas 到 Polars 六:在 Polars 中流式处理大型数据集

从 Pandas 到 Polars 0:理解Polars嵌套列类型

相关推荐
CodeCraft Studio2 天前
Excel处理控件Aspose.Cells教程:使用 Python 将 Pandas DataFrame 转换为 Excel
python·json·excel·pandas·csv·aspose·dataframe
njxiejing2 天前
Pandas数据结构(DataFrame,字典赋值)
数据结构·人工智能·pandas
Calihen的学习日志3 天前
【Pandas】3.1-数据预处理:列的基本操作
python·pandas
Source.Liu4 天前
【Python自动化】 21.2 Pandas 读取 Excel 时的 dtype 参数完全指南
python·自动化·pandas
Source.Liu4 天前
【Python自动化】 21 Pandas Excel 操作完整指南
python·excel·pandas
Source.Liu4 天前
【Python自动化】 21.1 Pandas 读取 Excel 文件的完整指南
python·自动化·pandas
偷心伊普西隆6 天前
Pandas DataFrame 指南
python·数据分析·pandas
chad__chang11 天前
Pandas的数据结构
数据结构·pandas
老歌老听老掉牙14 天前
Pandas DataFrame 列数操作完全指南
python·pandas
万粉变现经纪人14 天前
如何解决pip安装报错ModuleNotFoundError: No module named ‘websockets’问题
ide·pycharm·beautifulsoup·pandas·fastapi·pip·httpx