How to read numbers in python from csv file?

前端 未结 2 1966
有刺的猬
有刺的猬 2021-01-02 06:01

I have a csv file and I have to compute the mean for some of the columns. That\'s how I did:

file=csv.reader(open(\'tab.csv\',\'r\'))
n=[]
for row in file:
          


        
2条回答
  •  自闭症患者
    2021-01-02 07:05

    Just cast as you append:

     n.append(float(row[8]))
    

    If there are empty strings catch those before appending.

    try:
        n.append(float(row[8]))
    except ValueError:
       continue
    

    Or you might want to try pandas, in particular pandas.read_csv:

    import pandas as pd
    
    df = pd.read_csv("in.csv")
    print(df["col_name"].mean())
    

提交回复
热议问题