Python读取csv文件并存储变量

时间:2021-03-10 16:36:45

标签: python csv

我对 python 很陌生,所以这应该是一个相当简单的问题。我想从 csv 文件创建条形图。该文件包含两列,标题为“Latitude”和“TempAnom”。我希望能够读取 csv 文件并将数据存储为 lat 和 tAnom。实现这一目标的最佳方法是什么?

<头>
纬度 TempAnom
-89 0.06997871
-87 0.06997871

这是我迄今为止尝试过的,但我最终得到了一个 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'])

然后我应该能够执行以下操作来获取我的条形图:

    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()

尝试 2: 运行正确,但图表缺少数据

    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 应该有从 -89 到 89 的数据,但是有很多空白,并且 int(float(row1)) 将数据覆盖到最接近的整数。我想保留小数。

2 个答案:

答案 0 :(得分:1)

您将要导入 csv 并将变量声明为列表。因为 plt 将能够使用列表来显示数据。

import matplotlib.pyplot as plt
import csv

lat = []
tAnon = []

从那里您可以继续打开您拥有的 csv 文件,并将这些列中的数据附加到您的列表中。

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]))

然后你可以像上面一样绘制你的点。如果您对读取和写入 csv 仍然有点困惑,请检查一下。 https://realpython.com/python-csv/

答案 1 :(得分:0)

我的条形图没有按照我想要的方式显示,因为我的数据在需要为小数时转换为整数。我添加了“从十进制导入十进制”并将 int(float(row[1])) 更改为 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]))