簡體   English   中英

使用簡單的代碼獲取csv文件中整個列的平均值(在Python中)

[英]Using simple code to get the average (in Python) of an entire column in a csv file

我見過類似的問題,但是從來沒有人給出過簡單直接的pythonic答案。

我只是想獲取csv文件中“高”列的平均值。

import csv
import numpy as np    


with open('2010-Jan-June.csv', 'r', encoding='utf8', newline='') as f:
    highs = []
    for row in csv.DictReader(f, delimiter=','):
        high = int(row['high'])
print(sum(highs)/len(highs))

我的csv看起來像這樣:

date,high,low,precip
1-Jan,43,41,0
2-Jan,50,25,0
3-Jan,51,25,0
4-Jan,44,25,0
5-Jan,36,21,0
6-Jan,39,20,0
7-Jan,47,21,0.04
8-Jan,30,14,0
9-Jan,30,12,0

使用熊貓:

import pandas as pd

avg = pd.read_csv(r'/path/to/2010-Jan-June.csv', usecols=['high'], squeeze=True).mean()

請注意,使用純Python完全可以實現:

import csv
import statistics as stats

with open('2010-Jan-June.csv') as f:
    avg = stats.mean(row['high'] for row in csv.DictReader(f, delimiter=','))

print(avg)

由於您導入了numpy您可以像使用pandas一樣輕松地使用它:

從樣本的粘貼副本中讀取:

In [36]: txt="""date,high,low,precip
    ...: 1-Jan,43,41,0
    ...: 2-Jan,50,25,0
    ...: 3-Jan,51,25,0
    ...: 4-Jan,44,25,0
    ...: 5-Jan,36,21,0
    ...: 6-Jan,39,20,0
    ...: 7-Jan,47,21,0.04
    ...: 8-Jan,30,14,0
    ...: 9-Jan,30,12,0"""

numpy 1.14的Python3喜歡使用encoding參數:

In [38]: data = np.genfromtxt(txt.splitlines(),delimiter=',',dtype=None,names=True,
    ...: encoding=None)
In [39]: data
Out[39]: 
array([('1-Jan', 43, 41, 0.  ), ('2-Jan', 50, 25, 0.  ),
       ('3-Jan', 51, 25, 0.  ), ('4-Jan', 44, 25, 0.  ),
       ('5-Jan', 36, 21, 0.  ), ('6-Jan', 39, 20, 0.  ),
       ('7-Jan', 47, 21, 0.04), ('8-Jan', 30, 14, 0.  ),
       ('9-Jan', 30, 12, 0.  )],
      dtype=[('date', '<U5'), ('high', '<i8'), ('low', '<i8'), ('precip', '<f8')])

結果是一個結構化的數組,從中可以輕松選擇high場:

In [40]: data['high']
Out[40]: array([43, 50, 51, 44, 36, 39, 47, 30, 30])
In [41]: data['high'].mean()
Out[41]: 41.111111111111114

或者一行,只加載一列:

In [44]: np.genfromtxt(txt.splitlines(),delimiter=',',skip_header=1,usecols=[1]).mean()
Out[44]: 41.111111111111114

這是我嘗試使用csv庫的pythonic答案...

import csv
with open ('names.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    print sum(float(d['high']) for d in reader) / (reader.line_num - 1)

如果文件中沒有行,則除以0。

暫無
暫無

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

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