数据科学测试 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 天前
Pandas:从一个DataFrame中直接索引赋值到另一个索引位置出错的Bug及其解决方案
python·bug·pandas
Lx3523 天前
Pandas高级数据处理:数据安全与隐私保护
pandas
AuGuSt_814 天前
【对比】Pandas 和 Polars 的区别
pandas·polars
weixin_307779134 天前
PySpark检查两个DataFrame的数据是否一致
大数据·spark·pandas
鹿鸣悠悠5 天前
第二月:学习 NumPy、Pandas 和 Matplotlib 是数据分析和科学计算的基础
学习·numpy·pandas
PowerBI学谦6 天前
Python in Excel高级分析:一键RFM分析
大数据·人工智能·pandas
数据媛6 天前
机器学习_13 决策树知识总结
人工智能·python·决策树·机器学习·numpy·pandas·sklearn
数据媛6 天前
机器学习_18 K均值聚类知识点总结
python·机器学习·均值算法·numpy·pandas·scikit-learn·聚类
游王子11 天前
Python Pandas(9):Pandas 相关性分析
开发语言·python·pandas
游王子13 天前
Python Pandas(7):Pandas 数据清洗
开发语言·python·pandas