genfromtext read .csv with 3 columns返回ValueError'得到3列而不是2'?

时间:2017-11-14 05:32:38

标签: python csv matplotlib genfromtxt

我想要导入一个包含3列的.csv文件,其中第1列是我的x值,第2列是一个系列,第3列是另一个。我想在一个图上绘制两个系列,但是当我尝试读取csv文件并绘图时,它返回一个ValueError(见下文)。

import matplotlib.pyplot as plt
import numpy as np

dir = ""
file = "fig1data.csv"
fn = np.genfromtxt(file, delimiter=',')
x=fn[:,0]
y1=fn[:,1]
y2=fn[:,2]
plt.plot(x, y1, 'b', label=r"1913-1942 anomaly")
plt.plot(x, y2, 'r', label=r"$blah$")
plt.show()

返回错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-56-0d8440895d40> in <module>()
      4 dir = ""
      5 file = "fig1data.csv"
----> 6 fn = np.genfromtxt(file, delimiter=',')
      7 x=fn[:,0]
      8 y1=fn[:,1]

/usr/lib64/python3.4/site-packages/numpy/lib/npyio.py in genfromtxt(fname, dtype, comments, delimiter, skip_header, skip_footer, converters, missing_values, filling_values, usecols, names, excludelist, deletechars, replace_space, autostrip, case_sensitive, defaultfmt, unpack, usemask, loose, invalid_raise, max_rows)
   1767             # Raise an exception ?
   1768             if invalid_raise:
-> 1769                 raise ValueError(errmsg)
   1770             # Issue a warning ?
   1771             else:

ValueError: Some errors were detected !
    Line #2 (got 3 columns instead of 2)
    Line #3 (got 3 columns instead of 2)
    Line #4 (got 3 columns instead of 2)
    Line #5 (got 3 columns instead of 2)
    Line #6 (got 3 columns instead of 2)

1 个答案:

答案 0 :(得分:0)

您的.csv文件格式正确吗?

我能够让你的代码使用看起来像这样的.csv文件:

col1,col2,col3
0,0.0236852314846,10
1,0.0240463281472,20
2,0.0176584073052,30
3,0.0147662342087,40
4,0.0345340419842,50

但是,当我删除“col3”名称时,我收到了您看到的错误。因此,列名称的数量与您拥有的数据列数之间可能存在差异。