具有 3 列的文本读取.csv返回 ValueError "有 3 列而不是 2 列"?



我想导入一个包含 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)

您的.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"名称时,我收到了您看到的错误。因此,列名数与数据列数之间可能存在差异。

最新更新