gpt4 book ai didi

python - 使用 Python 从 CSV 文件中查找标准偏差

转载 作者:太空宇宙 更新时间:2023-11-04 01:07:30 25 4
gpt4 key购买 nike

我有一个名为'salaries.csv'的CSV文件,文件内容如下:

City,Job,Salary
Delhi,Doctors,500
Delhi,Lawyers,400
Delhi,Plumbers,100
London,Doctors,800
London,Lawyers,700
London,Plumbers,300
Tokyo,Doctors,900
Tokyo,Lawyers,800
Tokyo,Plumbers,400
Lawyers,Doctors,300
Lawyers,Lawyers,400
Lawyers,Plumbers,500
Hong Kong,Doctors,1800
Hong Kong,Lawyers,1100
Hong Kong,Plumbers,1000
Moscow,Doctors,300
Moscow,Lawyers,200
Moscow,Plumbers,100
Berlin,Doctors,800
Berlin,Plumbers,900
Paris,Doctors,900
Paris,Lawyers,800
Paris,Plumbers,500
Paris,Dog catchers,400

我需要打印每个职业工资的标准差。
这是旧版本的 Python。不能使用 statistics 和 numpy。

from __future__ import with_statement
import math
import csv
with open("salaries.csv") as f:
def average(f): return sum(f) * 1.0 / len(f)
variance = map(lambda x: (x - avg)**2, f)
standard_deviation = math.sqrt(average(variance))
print standard_deviation

谁能帮助我,我是 python 领域的新手。

Error : TypeError('argument 2 to map() must support iteration',)

输出应该是

管道工 311
律师 286
医生 448

最佳答案

要获取每个职业的详细信息,请创建一个字典:

from __future__ import with_statement
import math

def get_stats(profession, salaries):
n = float(len(salaries))
mean = sum(salaries)/n
stdev = 0
for value in salaries:
stdev += (value - mean)**2
stdev = math.sqrt(stdev/(n))
print profession, min(salaries), max(salaries), mean, stdev

with open('salaries.csv') as f:
f.readline()
# Create the list of salaries
salaries = {}
for line in f.readlines():
country, profession, value = line.split(',')
value = int(value.strip())
profession = profession.strip()
if salaries.has_key(profession):
salaries[profession].append(value)
else:
salaries[profession] = [value]
for k,v in salaries.items():
get_stats(k,v)

关于python - 使用 Python 从 CSV 文件中查找标准偏差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29640948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com