原计划:导入一个csv文件,然后算出平均值
import numpy as np
c=np.loadtxt('d:python36data.csv', delimiter=',', usecols=(2,), unpack=True)
print ("median =", np.median(c))
---------------------------
报错:OSerror: d:python36data.csv not found
找了半天原因:原来是data.csv应该是data_1.csv
后来以为编码问题
import numpy as np
import codecs
myfile='d:python36data_1.csv'
filecp = codecs.open(myfile, encoding='utf-8')
c=np.loadtxt(filecp, skiprows=2,dtype=int)
print ("median =", np.median(c))
---------------------------
报错:ValueError: could not convert string to float:’12,1,2,12’
搞了半天,没找到原因
去掉dtype=int后,报错IndexError:list index out of range
最终:
import numpy as np
import codecs
myfile='d:python36data_1.csv'
filecp = codecs.open(myfile, encoding='utf-8')
c=np.loadtxt(filecp, skiprows=2,delimiter=’,’, usecols=(2,),dtype=float)
print ("median =", np.median(c))
搞定,IndexError问题出在delimiter=’,’;而ValueError问题出在dtype=int和delimiter=’,’,因为没有delimiter=’,’隔开,就没法转换数据类型