If you allow the use of the standard library,
import math
xs = [0.5,0.7,0.3,0.2] # values (must be floats!)
mean = sum(xs) / len(xs) # mean
var = sum(pow(x-mean,2) for x in xs) / len(xs) # variance
std = math.sqrt(var) # standard deviation
If not, you need to approximate sqrt by hand. For example, you can use binary search or Newton's Method. Here's a wikipedia page for methods of doing so
If you allow the use of the standard library,
import math
xs = [0.5,0.7,0.3,0.2] # values (must be floats!)
mean = sum(xs) / len(xs) # mean
var = sum(pow(x-mean,2) for x in xs) / len(xs) # variance
std = math.sqrt(var) # standard deviation
If not, you need to approximate sqrt by hand. For example, you can use binary search or Newton's Method. Here's a wikipedia page for methods of doing so
with Python 3.4 and above there is a package called statistics, that has standard deviation (pstdev) and other functions
Here is an example of how to use it:
import statistics
data = [1, 1, 2.5, 6.5, 7.3, 8, 9.2]
print(statistics.pstdev(data))
# 3.2159043543498815
You can easily do this using pandas:
import pandas as pd
import numpy as np
df = pd.DataFrame([["AA", 1], ["AA", 3], ["BB", 3], ["CC", 5], ["BB", 2], ["AA", -1]])
df.columns = ["Category", "Score"]
print df.groupby("Category").apply(np.std)
I have a slight variation in the input data. I have more than one column, so how to give command to pick a specific column for the calculation of std deviation.
#Previous funtion
def compute_mean(my_list):
number_list = my_list
total = 0
for number in number_list:
total = total + float(number)
return total / len(number_list)
#The function I'm working on
def compute_sd(my_list):
list_of_numbers = my_list
sum = 0
for num in list_of_numbers:
mean = my_list
dev = num - mean
var = sum((l-mean)**2 for l in list) / len(list)
dev = math.sqrt(var)
return devThis is what I have so far, and I'm stumped.
In this step we will write a function (compute_sd) to calculate the standard deviation of the numbers in a list. It will receive a list of integer numbers as parameter and will return the standard deviation of the numbers in the given list. It will complete the task as follows:
· Use compute_mean function to calculate mean of the numbers in the list
· Initialize sum to 0
· Use definite loop (for num in list_of_numbers)
o Calculate deviation by subtracting mean from the num
o Calculate the square of the deviation
o Add the square of the deviation to sum
· Calculate the size of the list
· Divide sum by the size-1 to compute the result.
· Take the square root of the result to compute the standard deviation.
· Return the standard deviation of the numbers in the list.