Numpy loadtxt功能不起作用

时间:2018-03-20 06:27:07

标签: python python-3.x csv numpy

我使用的代码是:

import numpy as np
data=np.loadtxt('C:\\Users\\hp\\Desktop\\data.csv',delimiter=",")

为什么这不起作用 我将data.csv文件复制到上面指定的位置,但它不起作用。

我在jupyter文件夹中复制了csv文件,但它仍然无效 怎么了? 我正在使用python 3。

我得到的错误是

ValueError                                Traceback (most recent call last)
<ipython-input-14-498d125dea5e> in <module>()
      1 import numpy as np
----> 2 da=np.loadtxt('C:\\Users\\hp\\Desktop\\data.csv',delimiter=",")
~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin)
   1022 
   1023             # Convert each value according to its column and store
-> 1024             items = [conv(val) for (conv, val) in zip(converters, vals)]
   1025             # Then pack it according to the dtype's nesting
   1026             items = pack_items(items, packing)~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in <listcomp>(.0)
   1022 
   1023             # Convert each value according to its column and store
-> 1024             items = [conv(val) for (conv, val) in zip(converters, vals)]
   1025             # Then pack it according to the dtype's nesting
   1026             items = pack_items(items, packing)~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in floatconv(x)
    723         if b'0x' in x:
    724             return float.fromhex(asstr(x))
--> 725         return float(x)
    726 
    727     typ = dtype.type
ValueError: could not convert string to float: b'"32.502345269453"'

这是关于StackOverflow的第一个问题,任何有关问题的反馈都将受到高度赞赏,谢谢。

1 个答案:

答案 0 :(得分:0)

numpy并不支持通常的quotechar设置,但您仍然可以通过借用Python的CSV库来阅读它,如下所示:

import csv    
import numpy as np

with open('data.csv', newline='') as f_input:
    data = np.genfromtxt((','.join(row) for row in csv.reader(f_input)), delimiter=',')

print(data)

为您提供以下数据:

[[ 32.50234527  31.70700585]
 [ 53.42680403  68.77759598]
 [ 61.53035803  62.5623823 ]
 [ 47.47563963  71.54663223]
 ...
 [ 49.23976534  72.11183247]
 [ 50.03957594  85.23200734]
 [ 48.14985889  66.22495789]
 [ 25.12848465  53.45439421]]