Reading rows from a CSV file in Python

前端 未结 10 2199
慢半拍i
慢半拍i 2020-11-30 23:58

I have a CSV file, here is a sample of what it looks like:

Year:  Dec: Jan:
1      50   60
2      25   50
3      30   30
4      40   20
5      10   10


        
相关标签:
10条回答
  • 2020-12-01 00:46
    import csv
    
    with open('filepath/filename.csv', "rt", encoding='ascii') as infile:
        read = csv.reader(infile)
        for row in read :
            print (row)
    

    This will solve your problem. Don't forget to give the encoding.

    0 讨论(0)
  • 2020-12-01 00:50
    #  This program reads columns in a csv file
    import csv
    ifile = open('years.csv', "r")
    reader = csv.reader(ifile)
    
    # initialization and declaration of variables
    rownum = 0
    year = 0
    dec = 0
    jan = 0
    total_years = 0`
    
    for row in reader:
        if rownum == 0:
            header = row  #work with header row if you like
        else:
        colnum = 0
        for col in row:
            if colnum == 0:
                year = float(col)
            if colnum == 1:
                dec = float(col)
            if colnum == 2:
                jan = float(col)
            colnum += 1
        # end of if structure
    
    # now we can process results
    if rownum != 0:
        print(year, dec, jan)
        total_years = total_years + year
        print(total_years)
    
    # time to go after the next row/bar
    rownum += 1
    
    ifile.close()
    

    A bit late but nonetheless... You need to create and identify the csv file named "years.csv":

    Year Dec Jan 1 50 60 2 25 50 3 30 30 4 40 20 5 10 10

    0 讨论(0)
  • 2020-12-01 00:50

    One can do it using pandas library.

    Example:

    import numpy as np
    import pandas as pd
    
    file = r"C:\Users\unknown\Documents\Example.csv"
    df1 = pd.read_csv(file)
    df1.head()
    
    0 讨论(0)
  • 2020-12-01 00:54

    I just leave my solution here.

    import csv
    import numpy as np
    
    with open(name, newline='') as f:
        reader = csv.reader(f, delimiter=",")
        # skip header
        next(reader)
        # convert csv to list and then to np.array
        data  = np.array(list(reader))[:, 1:] # skip the first column
    
    print(data.shape) # => (N, 2)
    
    # sum each row
    s = data.sum(axis=1)
    print(s.shape) # => (N,)
    
    0 讨论(0)
提交回复
热议问题