【问题标题】:genfromtext reading .csv with 3 columns returns ValueError 'got 3 columns instead of 2'?genfromtxt 读取 3 列的 .csv 返回 ValueError '得到 3 列而不是 2'?
【发布时间】:2018-04-26 23:06:28
【问题描述】:

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

【问题讨论】:

    标签: python csv matplotlib genfromtxt


    【解决方案1】:

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

    【讨论】:

    • @DavidG 是的,我相信。我有 3 列带有标题。我唯一能看到导致问题的就是缺失值。看我数据的前几行:year,anomaly,global 1880,, 1881,3.178055556, 1882,0.678055556,-4.6 1883,-0.980277778,-4.7 1884,-2.888611111,-5.2 1885,1.444722222,-5. >
    • @vitalie 您的第一行数据中“1880”之后的两个逗号是否是拼写错误?因为应该只有一个逗号分隔一行中的元素。另外,你的行是用换行符还是空格分隔的?你能把你的前几行按照我上面的格式发布一下吗?
    • 我实际上修复了它,您的评论有助于由于某种原因没有标题导致错误。我切换到 np.loadtxt() 并添加了解决问题的标题。郑重声明,这两个逗号不是拼写错误,它们旨在表示一个包含两个缺失数据点的 3 列字段
    猜你喜欢
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 2017-01-22
    相关资源
    最近更新 更多