簡體   English   中英

如何對列表列表的特定部分使用統計信息

[英]How to use statistics on a specific portion of a list of lists

我有一個文本文件,其中包含以下 365 個條目的縮寫列表,每個條目都在一行中。 第一個條目代表日期,第二個條目代表道瓊斯指數

8/28/2018|26064.01953
8/29/2018|26124.57031
8/30/2018|25986.91992    

我正在使用以下代碼:

import os
import math
import statistics
def main ():
    infile = open('DJI.txt', 'r')
    values = infile.read()
    infile.close()
    values=values.split("\n")
    values=[value.split("|")for value in values]
    avg = sum([float(l[1]) for l in values])/len(values)
    highest = max([float(l[1]) for l in values])
    lowest = min([float(l[1]) for l in values])
    values.sort(key = lambda x:x[1])
    print(avg)
    print(highest)
    print(lowest)
    print(values)
main()

我正在努力解決此代碼的另外 2 個任務,首先是找到每月的平均收盤值,而不是全年的平均值。

二是對於最高和最低的函數,數值發生的日期也應該和數值一起顯示。

非常感謝您的幫助。

使用pandas ,可以很容易地實現此功能:

我的輸入文件:(注意額外的月份數據以檢查每月平均值)

8/28/2018|26064.01953
8/29/2018|26124.57031
8/30/2018|25986.91992
9/28/2018|26064.01953
9/29/2018|25124.57031
9/30/2018|25986.91992

讀取輸入文件:

>>> import pandas as pd
>>> df = pd.read_csv("input.txt", '|', header=None, names=["Date", "Dow-Jones Value"], parse_dates=["Date"])
>>> df
        Date  Dow-Jones Value
0 2018-08-28      26064.01953
1 2018-08-29      26124.57031
2 2018-08-30      25986.91992
3 2018-09-28      26064.01953
4 2018-09-29      25124.57031
5 2018-09-30      25986.91992

檢索統計信息:

>>> df['Dow-Jones Value'].mean() # average
25891.836586666668

>>> df.iloc[df['Dow-Jones Value'].idxmax()] # highest
Date               2018-08-29 00:00:00
Dow-Jones Value                26124.6
Name: 1, dtype: object

>>> df.iloc[df['Dow-Jones Value'].idxmin()] # lowest
Date               2018-09-29 00:00:00
Dow-Jones Value                25124.6
Name: 4, dtype: object

>>> df.sort_values('Dow-Jones Value') # sorted by Dow-Jones Value
        Date  Dow-Jones Value
4 2018-09-29      25124.57031
2 2018-08-30      25986.91992
5 2018-09-30      25986.91992
0 2018-08-28      26064.01953
3 2018-09-28      26064.01953
1 2018-08-29      26124.57031

>>> df.groupby(pd.Grouper(key='Date', freq='M')).mean() # Monthly Averages
            Dow-Jones Value
Date                       
2018-08-31     26058.503253
2018-09-30     25725.169920

下面的解決方案不使用任何外部庫

from collections import defaultdict

monthly_data = defaultdict(list)

with open('DJI.txt') as f:
  lines = [l.strip() for l in f.readlines()]
  for line in lines:
    values = line.split('|')
    date = values[0]
    month = date.split('/')[0]
    value = float(values[1])
    monthly_data[month].append((value,date))
for month,values in monthly_data.items():
  _values = [v[0] for v in values]
  avg = sum(_values)/len(_values)
  _min = min(values, key=lambda x: x[0])
  _max = max(values, key=lambda x: x[0])
  print('Month: {}. avg value {}, min value {}, max value {}'.format(month,avg,_min,_max))

大疆.txt

8/28/2018|26064.01953
8/29/2018|26124.57031
8/30/2018|25986.91992
9/28/2018|16064.01953
9/10/2018|12.99
9/29/2018|16124.57031
9/30/2018|15986.91992 
9/12/2018|999999.91992

輸出

Month: 8. avg value 26058.503253333332, min value (25986.91992, '8/30/2018'), max value (26124.57031, '8/29/2018')
Month: 9. avg value 209637.68393600002, min value (12.99, '9/10/2018'), max value (999999.91992, '9/12/2018')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM