0

我有一个包含数据的 CSV 文件,例如

350, -0.042447984
349, -0.041671798
348, -0.04158416
347, -0.041811798
346, -0.041716855

虽然我有更多的数据。我要做的是将第一列(350、349 等)定义为我的 x 值,将第二列(-0.042447984、-0.041671798 等)定义为我的 y 值。到目前为止,这是我的代码:

import pylab
x=[350, 349, 348, 347, 346]
y=[-0.042447984, -0.041671798, -0.04158416, -0.041811798, -0.041716855]
pylab.plot(x, y)
pylab.show()

但是,我没有手动输入数字,而是尝试编写一个程序,该程序将从我的 CSV 文件中提取第 1 列作为 x 值,将第 2 列提取为 y 值。这可能比我尝试做的要简单得多。我是python的新手,所以请耐心等待!

4

3 回答 3

2

假设您的 csv 文件采用您描述的格式,我可能会使用loadtxt.

>>> d = numpy.loadtxt("plot1.csv", delimiter=",")
>>> d
array([[  3.50000000e+02,  -4.24479840e-02],
       [  3.49000000e+02,  -4.16717980e-02],
       [  3.48000000e+02,  -4.15841600e-02],
       [  3.47000000e+02,  -4.18117980e-02],
       [  3.46000000e+02,  -4.17168550e-02]])

并且有很多方法可以从中获取xy获取:

>>> x,y = numpy.loadtxt("plot1.csv", delimiter=",", unpack=True)
>>> x
array([ 350.,  349.,  348.,  347.,  346.])
>>> y
array([-0.04244798, -0.0416718 , -0.04158416, -0.0418118 , -0.04171685])

x,y = d.Td[:,0], d[:,1]

格式越复杂,csv直接使用模块就越好。尽管loadtxt有很多选择,但您通常需要比它提供的更精细的控制。

于 2012-07-27T19:00:59.463 回答
1

这将使您开始:

import csv

with open('data.txt') as inf:
    x = []
    y = []
    for line in csv.reader(inf):
        tx, ty = line
        x.append(int(tx))
        y.append(float(ty))

列表xy并将分别包含:

[350, 349, 348, 347, 346]
[-0.042447984, -0.041671798, -0.04158416, -0.041811798, -0.041716855]

备注

with当我们完成文件或遇到异常时,使用来打开文件将负责关闭它。csv模块将逐行读取输入数据,并根据逗号分隔符将每一行拆分为一个列表。第一项被转换为int,第二项被转换为float之前被附加到各自的列表。

文件data.txt包含您的示例数据。

于 2012-07-27T18:55:19.240 回答
1

我知道这篇文章已经过时了;但是,对于需要快速绘制 csv 数据的人来说,以下脚本将提供一个很好的解决方案。

它展示了如何从 csv 文件中导入数据,以及如何使用 matplotlib 制作一个绘图,该绘图将制作一个 png 并绘制它。

使用没有标题的休伦湖数据,你会得到一个很好的情节。

import csv
import matplotlib.pyplot as plt
from numpy import arange

#####################################
# instatiation of variables

filehandle = "lake_huron.csv"
x_data = []                         # makes a list
y_data = []                         # makes a list
png_filename = 'LakeData.png'

#####################################
# opening csv file and reading

my_file = open(filehandle, "rb")    # opens file for reading
data = csv.reader(my_file)          # saves file to variable "data"

#####################################
# saves csv data to x_data and y_data

for row in data:
    x_data.append(eval(row[1]))     # selects data from the ith row
    y_data.append(eval(row[2]))     # selects data from the ith row

#####################################
# closes csv file
my_file.close()                     # closes file




#####################################
# makes plot (show) and saves png

fig = plt.figure()                  # calls a variable for the png info

# defines plot's information (more options can be seen on matplotlib website)
plt.title("Level of Lake Huron from 1875 to 1972")      # plot name
plt.xlabel('Year')                                      # x axis label
plt.ylabel('Lake Level (in feet)')                      # y axis label
plt.xticks(arange(1875,1973,10))                        # x axis tick marks
plt.axis([1875,1973,573,584])                           # x and y ranges

# defines png size
fig.set_size_inches(10.5,5.5)                           # png size in inches

# plots the data from the csv above
plt.plot(x_data,y_data)

#saves png with specific resolution and shows plot
fig.savefig(png_filename ,dpi=600, bbox_inches='tight')     # saves png
plt.show()                                                  # shows plot

plt.close()                                                 # closes pylab
于 2015-10-01T03:58:21.740 回答