首页 > 解决方案 > 如何在 Python 中使用 enumerate 来计算列表的 STD?

问题描述

我正在尝试计算 list 的标准差vr。列表大小为 32,包含大小为 3980 的数组。该数组表示给定height(3980 高度)的值。

首先,我将数据分成 15 分钟的块,其中分钟以raytimes. raytimes也是一个大小列表32(仅包含观察时间vr)。

我想要在每个height级别计算标准偏差,这样我最终得到一个 size 数组3980。这在我的代码中正常。但是,当我测试它时,我的代码不会产生正确的标准偏差值——也就是说,输出到 等的值w1sd不正确(但是数组的大小是正确的:元素w2sd数组)。3980我假设我在计算标准偏差时混淆了错误的指数。

以下是数据集中的示例值。所有数据都应落入本示例中提供的所有数据均在 15 分钟内 (< 0.25) w1。我想计算 的第一个元素的标准偏差,即 的标准偏差,然后是第二个元素的标准偏差,或等的标准偏差。结果应该是但下面的代码给出了in 。是我的索引有问题吗?w1sdraytimesvr2.0 + 3.1 + 2.13.1 + 4.1 + nanw1sd[0.497, 0.499, 1.0, 7.5]nanstdw1sd = [0.497, 0.77, 1.31, 5.301]nanstd

vr = [
    [2.0, 3.1, 4.1, nan],
    [3.1, 4.1, nan, 5.1],
    [2.1, nan, 6.1, 20.1]
]
Height = [10.0, 20.0, 30.0, 40]
raytimes = [0, 0.1, 0.2]

for j, h in enumerate(Height): 
    for i, t in enumerate(raytimes):
        if raytimes[i] < 0.25:
            w1.append(float(vr[i][j]))
        elif 0.25 <= raytimes[i] < 0.5:
            w2.append(float(vr[i][j]))
        elif 0.5 <= raytimes[i] < 0.75:
            w3.append(float(vr[i][j]))
        else:
            w4.append(float(vr[i][j]))
    w1sd.append(round(nanstd(w1), 3))
    w2sd.append(round(nanstd(w2), 3))
    w3sd.append(round(nanstd(w3), 3))
    w4sd.append(round(nanstd(w4), 3))
    w1 = []
    w2 = []
    w3 = []
    w4 = []

标签: pythonenumeratestandard-deviation

解决方案


我会考虑使用pandas这个。它是一个库,可以有效处理numpy数组中的数据集,并让所有的循环和索引从你手中解放出来。

在这种情况下,我将定义dataframe带有N_raytimes行和N_Height列的 a,这将允许以您喜欢的任何方式轻松地对数据进行切片和聚合。

此代码给出了预期的输出。

import pandas as pd
import numpy as np

vr = [
    [2.0, 3.1, 4.1, np.nan],
    [3.1, 4.1, np.nan, 5.1],
    [2.1, np.nan, 6.1, 20.1]
]
Height = [10.0, 20.0, 30.0, 40]
raytimes = [0, 0.1, 0.2]

# Define a dataframe with the data
df = pd.DataFrame(vr, columns=Height, index=raytimes)
df.columns.name = "Height"
df.index.name = "raytimes"

# Split it out (this could be more elegant)
w1 = df[df.index < 0.25]
w2 = df[(df.index >= 0.25) & (df.index < 0.5)]
w3 = df[(df.index >= 0.5) & (df.index < 0.75)]
w4 = df[df.index >= 0.75]

# Compute standard deviations
w1sd = w1.std(axis=0, ddof=0).values
w2sd = w2.std(axis=0, ddof=0).values
w3sd = w3.std(axis=0, ddof=0).values
w4sd = w4.std(axis=0, ddof=0).values

推荐阅读