数据科学测试 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嵌套列类型

相关推荐
白杆杆红伞伞3 小时前
01_快速入门
python·pandas
diaobusi-882 天前
Python数据分析 Pandas基本操作
python·数据分析·pandas
D11_3 天前
pandas:读取各类文件方法以及爬虫时json数据保存
爬虫·python·数据分析·json·pandas
diaobusi-883 天前
python数据分析 pandas库-数据的读取和保存
python·数据分析·pandas
神奇夜光杯3 天前
Python酷库之旅-第三方库Pandas(117)
开发语言·人工智能·python·excel·pandas·标准库及第三方库·学习与成长
TuringSnowy4 天前
Pandas_sqlite
python·pandas
小白学大数据4 天前
Pandas与Matplotlib:Python中的动态数据可视化
开发语言·爬虫·python·pandas·matplotlib
aloha_7894 天前
如何理解深度学习的训练过程
人工智能·python·深度学习·numpy·virtualenv·pandas·scikit-learn
wyk123_0464 天前
pandas 生成excel多级表头
python·excel·pandas
码农超哥同学5 天前
Python知识点:如何使用Python进行Excel文件操作(OpenPyXL、Pandas)
python·面试·excel·pandas·编程