python - 如何在 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 。是我的索引有问题吗?w1sd
raytimes
vr
2.0 + 3.1 + 2.1
3.1 + 4.1 + nan
w1sd
[0.497, 0.499, 1.0, 7.5]
nanstd
w1sd = [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 = []
解决方案
我会考虑使用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
推荐阅读
- php - 如何包含应该内置的缺少的 PHP 函数?
- swift - 未捕获的异常 'NSInvalidArgumentException',原因:'-[UIViewController tableView:numberOfRowsInSection:]:无法识别的选择器发送到实例
- c# - 将 WebClient.DownloadString 的结果拆分为多行
- scala - 我如何让生成的 Json 有一个非此即彼的输出场景?
- ios - 如何使用元数据丰富 UIImage 数据
- c++ - 为什么我的 C++ 代码中出现链接器命令失败错误?
- go - 如何为 golang tcp 服务器配置 GKE 负载均衡器?
- ios - 如何优化我的应用程序以更流畅地运行?
- javascript - Ajax PUT 请求成功但未在数据库上更新
- api - 如何使用嵌套(复杂)JSON(下面提供的 JSON 示例)在机器人框架(请求库)中执行 Post 请求