首页 > 解决方案 > 在 Python 中转换此标准差 Excel 公式

问题描述

请问有人可以帮我把这个excel公式转换成python吗?这是我想用来计算两个列表之间每个样本点的标准偏差的公式。

这是我的 2 个列表(虚拟数据):

P=[121,43.4,122.2,43.98]
N= [341,111,232,123]

Excel公式: =SQRT(P*((1-P)/N))

我的python代码是:

my_data=[]
for p in list_p:
    for n in list_n:
        data= p*((1-p)/n))
        squared=sqrt(data)
        my_data.append(squared)

请问有人可以帮我吗?

谢谢你。

标签: pythonexcelfor-loopmath

解决方案


鉴于您的 值p,您正试图获得负数的平方根,这将提高 a ValueError: math domain error。假设您使用已定义平方根的数字(例如,p在 [0, 1] 中),我在下面写下了我的答案。

您的 excel 公式到 python 的翻译可以是:

import math

def f(p, n):
    return math.sqrt(p * ((1 - p) / n))

然后,您可以使用zip同时遍历两个列表并应用您的函数。

p = [0.1, 0.2, 0.3, 0.4]
n = [341, 111, 232, 123]

results = []
for this_p, this_n in zip(p, n):
    result = f(p=this_p, n=this_n)
    results.append(result)

您也可以将其写为列表理解。

results = [f(i, j) for (i, j) in zip(p, n)]

两种方法都给出了这个输出

[0.01624591083221647,
 0.03796631983009996,
 0.030086083390715772,
 0.04417261042993862]

推荐阅读