Python读取csv文件并存储变量

2024-09-28 21:01:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

^{tb1}$

这是我到目前为止尝试过的,但我最终得到一个关键错误:“纬度”:

    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))将数据覆盖到最接近的整数。我想保留小数


Tags: 文件csv数据aspltfilenamepointsreader
2条回答

我的条形图没有按我想要的方式显示,因为当数据需要小数时,我将数据转换为整数。我添加了“from decimal import decimal”,并将int(float(第[1]行))更改为decimal(第[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]))

您需要导入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/

相关问题 更多 >