简体   繁体   中英

Python read csv file and store variables

I am pretty new to python, so this should be a fairly easy question. I want to create a bar graph from a csv file. The file contains two columns with the headers "Latitude" and "TempAnom". I want to be able to read in the csv file and store the data as lat and tAnom. What is the best way to accomplish this?

Latitude TempAnom
-89 0.06997871
-87 0.06997871

This is what I've tried so far, but I end up getting a KeyError: 'Latitude':

    filename='2016_tAnoms.csv'

    lat = []
    tAnom = []
    with open(filename,'r') as csv_file:
      csv_reader = csv.DictReader(csv_file, delimiter=',')
      for row in csv_reader:
        lat.append(row['Latitude'])
        tAnom.append(row['TempAnom'])

Then I should be able to do the following to obtain my bar graph:

    import matplotlib.pyplot as plt

    plt.bar(lat,tAnom)
    plt.title('2016 Temperature Anomalies by Latitude Band')
    plt.xlabel('Latitude')
    plt.ylabel('Temperature Anomaly (°C)')
    plt.show()

Attempt 2: Runs correctly, but graph is missing data

    filename='2016_tAnoms.csv'

    lat = []
    tAnom = []
    with open(filename,'r') as csvfile:
      points = csv.reader(csvfile, delimiter=',')
      next(points)
      for row in points:
        lat.append(int(row[0]))
        tAnom.append(int(float(row[1])))

Produced Graph There should be data from -89 to 89, but there's a lot of blanks and the int(float(row 1 )) is covering the data to the nearest integer. I want to keep the decimals.

You are going to want to import csv and declare your variables as lists. Since plt will be able to use the list to display the data.

import matplotlib.pyplot as plt
import csv

lat = []
tAnon = []

From there you can go ahead and open the csv file you have and append your lists with the data in those columns.

with open('filename', 'r') as csvfile:
    points = csv.reader(csvfile, delimiter=',')
    for row in points:
        lat.append(flaot(row[0]))
        tAnon.append(float(row[1]))

Then you can plot your points like you have above. check this out if you are still a bit confused on reading and writing csv. https://realpython.com/python-csv/

My bar graph was not displaying the way I wanted it, because I had my data converted to integers when they needed to be decimals. I added "from decimal import Decimal" and changed the int(float(row[1])) to Decimal(row[1]).

    from decimal import Decimal

    filename='2016_tAnoms.csv'

    lat = []
    tAnom = []
    with open(filename,'r') as csvfile:
      points = csv.reader(csvfile, delimiter=',')
      next(points)
      for row in points:
        lat.append(int(row[0]))
        tAnom.append(Decimal(row[1]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM