问题描述
我在e:\dir1\datafile.csv
处有一个CSV文件.它包含三列,需要跳过10条标题行和尾随行.我想用numpy.loadtxt()绘制它,但我没有找到任何严格的文档.
I have a CSV file at e:\dir1\datafile.csv
.It contains three columns and 10 heading and trailing lines need to be skipped.I would like to plot it with numpy.loadtxt(), for which I haven't found any rigorous documentation.
这是我在网上找到的几次尝试中开始写的东西.
Here is what I started to write from the several tries I found on the web.
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
def read_datafile(file_name):
# the skiprows keyword is for heading, but I don't know if trailing lines
# can be specified
data = np.loadtxt(file_name, delimiter=',', skiprows=10)
return data
data = read_datafile('e:\dir1\datafile.csv')
x = ???
y = ???
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_title("Mains power stability")
ax1.set_xlabel('time')
ax1.set_ylabel('Mains voltage')
ax1.plot(x,y, c='r', label='the data')
leg = ax1.legend()
plt.show()
推荐答案
根据 docs numpy.loadtxt
是
因此只有少数选项可以处理更复杂的文件.如前所述, numpy.genfromtxt
具有更多选项.因此,举例来说,您可以使用
so there are only a few options to handle more complicated files.As mentioned numpy.genfromtxt
has more options. So as an example you could use
import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
skip_footer=10, names=['x', 'y', 'z'])
读取数据并为列分配名称(或使用names=True
从文件中读取标题行),然后使用
to read the data and assign names to the columns (or read a header line from the file with names=True
) and than plot it with
ax1.plot(data['x'], data['y'], color='r', label='the data')
我认为numpy现在已被很好地记录下来.您可以从 ipython
或使用IDE轻松检查文档字符串例如 spider
,如果您希望阅读以HTML格式呈现的内容.
I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython
or by using an IDE like spider
if you prefer to read them rendered as HTML.
这篇关于使用matplotlib从CSV文件绘制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!