【问题标题】:fetch values from csv with different number of columns in csv, numpy从csv中获取具有不同列数的值,numpy
【发布时间】:2017-02-15 12:47:08
【问题描述】:

我正在使用

读取 csv
numpy.genfromtxt(csv_name, delimiter=',') 

但我无法这样做,因为我的 csv 每行包含不同的列数。

o/p:

ValueError: Some errors were detected
 Line #2 (got 8 columns instead of 7)
 Line #3 (got 8 columns instead of 7)
 Line #4 (got 8 columns instead of 7)
 Line #6 (got 8 columns instead of 7)
 Line #7 (got 5 columns instead of 7)
 Line #8 (got 5 columns instead of 7)
 Line #9 (got 5 columns instead of 7)
 Line #10 (got 5 columns instead of 7)

可以用numpy做吗?

【问题讨论】:

标签: python numpy


【解决方案1】:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html,您可以使用genfromtxtfilling_values 参数来实现。

否则,您可以使用此答案:Python: How to read a data file with uneven number of columns

【讨论】:

    【解决方案2】:

    如果可以将读取的数据限制为所有行的公共列数,您可以使用usecols 显式选择要读取的列,例如:

    numpy.genfromtxt(csv_name, delimiter=',', usecols=range(4))
    

    【讨论】:

    • 这可能与您的 CSV 文件中的实际数据有关。需要数据样本来澄清这一点。
    • 您可能需要指定dtype
    猜你喜欢
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 2017-09-09
    • 2018-10-05
    相关资源
    最近更新 更多