0

Please could someone help me convert this excel formula into python? This is the formula I would like to use to calculate the standard deviation for each sample point between 2 lists.

Here are my 2 lists (dummy data):

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

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

My python code is:

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

Please could someone help me out?

Thank you.

  • Does this answer your question? [ValueError: math domain error](https://stackoverflow.com/questions/15890503/valueerror-math-domain-error) – Anurag Reddy Oct 05 '20 at 14:32

1 Answers1

0

Given your values for p, you are attempting to get the square root of a negative number, which will raise a ValueError: math domain error. I have written my answer below assuming that you use numbers that have defined square roots (e.g., p in [0, 1]).

The translation of your excel formula to python can be:

import math

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

Then, you can use zip to iterate through both lists at the same time and apply your function.

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)

You can also write this as a list comprehension.

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

Both methods give this output

[0.01624591083221647,
 0.03796631983009996,
 0.030086083390715772,
 0.04417261042993862]
jkr
  • 17,119
  • 2
  • 42
  • 68
  • Thanks so much! I get `unsupported operand type(s) for -: 'int' and 'list'`, when inputting into function f, both are lists so not sure why this is happening? –  Oct 05 '20 at 17:37
  • You aren't copying and pasting my answer in that case. What did you change? – jkr Oct 05 '20 at 18:01
  • changed my p vals to:`p = [30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6]` and n values are similar to the numbers above, same list length. now I get 'math domain error' –  Oct 05 '20 at 18:14
  • sorry I had to divide my values by 100 as they are percentages - it worked after this! thanks so much –  Oct 05 '20 at 18:35