Skip to content Skip to sidebar Skip to footer

How To Find Avg Of Column Of Csv File

import csv with open('Met.csv', 'r') as f: reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE) for row in reader: print row I am not able to go ahead how

Solution 1:

Try pandas instead of reading from csv

import pandas as pd
data = pd.read_csv('Met.csv')

It is far easier to grab columns and perform operations using pandas. Here I am loading the csv contents to a dataframe.

Loaded data : (sample data)

>>> data
       name   id nametype     recclassmass0    Aarhus    2    Valid           H6     7201      Abee    6    Valid          EH4  1070002  Acapulco   10    Valid  Acapulcoite     9143   Achiras  370    Valid           L6     7804  Adhi Kot  379    Valid          EH4    42395     Adzhi  390    Valid        LL3-69106      Agen  392    Valid           H5   30000

Just the Mass column :

You can access individual columns as data['column name']

>>>data['mass']
0       720
1    107000
2       914
3       780
4      4239
5       910
6     30000
Name: mass, dtype: int64

Average of Mass column :

>>>data['mass'].mean()
20651.857142857141

Solution 2:

You can use csv.DictReader() instead of csv.reader(). The following code works fine to me

import csv

mass_list = []
withopen("../data/Met.csv", "r") as f:
    reader = csv.DictReader(f, delimiter="\t")
    for row in reader:
        mass = row["mass"]
        if mass isnotNoneand mass isnot"--":
            mass_list.append(float(row["mass"]))

avg_mass = sum(mass_list) / len(mass_list)
print"avg of mass: ", avg_mass

Hope it helps.

Post a Comment for "How To Find Avg Of Column Of Csv File"