Python:每年平均价格

时间:2017-11-01 03:20:34

标签: python list file average

有人能帮助我以下吗?我试图创建一个可以打开" notepad.txt"提交并计算10月份的平均价格。

notepad.txt
10-15-2012:3.886
10-22-2012:3.756
10-29-2012:3.638


infile = open('notepad.txt', 'r')

def clean_data():

    line1 = infile.readline()
    split1 = line1.rstrip('\n')
    items = split1[0].split('-')
    del items[0]
    del items[0]
    master = []
    master = master + split1 + items
    master = list(map(float, master))
    print(master)
    print(total)
    line1 = infile.readline()
clean_data()

4 个答案:

答案 0 :(得分:0)

打印并返回平均值

def clean_data(infile):
    lines = infile.readlines()
    total = 0.0
    num = 0
    for line in lines:
        spl = line.strip().split(":")
        total += float(spl[len(spl)-1])
        num += 1
    average = total/num
    print(average)
    return average

答案 1 :(得分:0)

def sum_data():
    n,c = 0,0
    with  open('notepad.txt', 'r') as infile:
        x = infile.readline()
        # for october 10
        if x[:3]=='10-' and x[6:10]=='2010';
            n += float(x[12:])
            c += 1
    print(n/c)

答案 2 :(得分:0)

如果你想使用熊猫:

from io import StringIO
import pandas as pd

notepadtxt = StringIO("""10-15-2012:3.886
10-22-2012:3.756
10-29-2012:3.638""")

df = pd.read_csv(notepadtxt, sep='\:',header=None, engine='python')

df[0] = pd.to_datetime(df[0])

df=df.set_index(0)

df.resample('M').mean().values[0][0]

输出:

3.7600000000000002

答案 3 :(得分:0)

以下vanilla Python代码应该足够了:

infile = open('notepad.txt', 'r')

def clean_data():
    data = []
    for line in infile:
            data.append(line.strip().split(':'))
    values = []
    for value in data:
        values.append(float(value[1]))
    avg_price = sum(values)/len(values)
    print(avg_price)

clean_data()
infile.close()