gpt4 book ai didi

python - 使用简单代码获取 csv 文件中整个列的平均值(在 Python 中)

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

我见过类似的问题,但从来没有一个给出简单直接的 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

最佳答案

使用 Pandas :

import pandas as pd

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

关于python - 使用简单代码获取 csv 文件中整个列的平均值(在 Python 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49471081/

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