CSV文件阅读器

时间:2019-04-12 01:15:47

标签: python python-3.x

我应该创建一个读取csv文件的python函数。我已经写了大部分,只有几个问题。首先,我的平均值,最小值和最大值都给了我相同的数字,我不知道这是怎么回事。最后,我不知道如何处理标准偏差。我非常感谢您的帮助。 我还应该得到最小值0.580,最大值1.552,平均值1.0228和标准偏差0.14654。 另外,在数据点上,我仅应使用第2列。

import csv
import statistics

def fileread03 (file):
    Data=[]
    with open(file, newline='') as In_file:
        reader=csv.reader(In_file, delimiter=",")
        Header=False
        for row in reader:
            if Header:
                Header=True
                HeaderInfo=row
        else:
            Data.append(float(row[1]))

    avg=statistics.mean(Data)
    mini=min(Data)
    maxi=max(Data)

    print (file,"Column 2 has minimum of",mini,"and maximum of",maxi)      
    print (file,"Column 2 has a mean of","%f"%(avg),"with","%d"%(reader.line_num),"data points")
    print (file,"Column 2 standard deviation is %s"%(statistics.stdev(Data)))

我还没有弄清楚如何将我的数据发布为链接,所以我将其粘贴。我很抱歉。

1,1.03022387
2,1.038002145
3,1.035830101
4,1.034994363
5,1.031323334
6,1.038452321
7,1.043062609
8,1.038032379
9,1.0364557
10,1.032418438
11,1.035486002
12,1.034489151
13,1.042182439
14,1.036726578
15,1.040725664
16,1.04258192
17,1.033622994
18,1.0353206
19,1.036432256
20,1.039528582
21,1.037882773
22,1.03727257
23,1.037687353
24,1.031052011
25,1.03824202
26,1.042547636
27,1.041188157
28,1.040335043
29,1.039175566
30,1.039636431
31,1.037803898
32,1.041778196
33,1.034893874
34,1.031176139
35,1.033263496
36,1.043093701
37,1.043429697
38,1.001
39,1.04113086
40,1.037847987
41,1.032391964
42,1.040356843
43,1.037036769
44,1.039085609
45,1.036347304
46,1.040578085
47,1.037387121
48,1.038344488
49,1.031850887
50,1.040082844
51,0.985461896
52,0.826852007
53,0.797357281
54,1.005512301
55,1.00039709
56,1.222802255
57,1.142375769
58,1.352032893
59,1.112897551
60,0.87815325
61,1.105341595
62,1.068324568
63,0.677663188
64,0.796153856
65,1.008681073
66,0.580124268
67,1.114469402
68,0.775473003
69,0.662000558
70,1.215449602
71,1.190480987
72,1.042210619
73,0.779978889
74,0.978878568
75,1.103720987
76,1.171154216
77,1.552026816
78,0.863948023
79,0.851098845
80,0.838314475
81,0.858669262
82,1.019072619
83,0.787732957
84,0.813981183
85,1.199212974
86,0.846172396
87,1.165392635
88,1.14476665
89,1.34478376
90,1.501
91,1.018674479
92,1.092147525
93,0.827845253
94,0.941279736
95,0.892973283
96,1.168058418
97,0.779913496
98,1.174240444
99,1.078392083
100,1.084858149

1 个答案:

答案 0 :(得分:0)

您需要缩进'else'块,这是我的版本:

def fileread03(file):
Data=[]
stats = {}
with open(file, newline='') as In_file:
    reader=csv.reader(In_file, delimiter=",")
    Header=False
    for row in reader:
        if Header:
            Header=True
            HeaderInfo=row
        else:
            Data.append(float(row[1]))

stats['avg'] = statistics.mean(Data)
stats['min'] = min(Data)
stats['max'] = max(Data)
return stats

执行后的结果如下:

file_stats = fileread03('data-stackOver.csv')

出局:

{'avg': 1.02278293901, 'min': 0.580124268, 'max': 1.552026816}