ValueError:无法将字符串转换为float:'1.csv'

时间:2018-01-25 11:28:24

标签: python csv

我在Python 3.6.3上获得ValueError: could not convert string to float: '1.csv',代码如下:

import numpy as np
import matplotlib.pyplot as plt
from lmfit import Model

'''####### functions #####'''
def moving_average(a, n=3) :
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

# Fitting function
def gaussian(x,a,x0,w):
    return a*np.exp(-2*(x-x0)**2/w**2)

'''#######  file name ######'''

savfile = False

file_n = ['1','2','3','4','5','6','7','8','9','10',
          '11','12','13','14','15','16','17','18','19','20','21','22','23','24']


# hole number of reference
dist = [3,5,7,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,27,29,32,36,38]
dist = np.array(dist,dtype=float)*1e-3*25 +1e-3*25 +1e-3*230 

'''####### flags representing which point on chopper #######'''
'''####### the razor initiates the plot, as beam diverges #######'''

flag = [0,0,1,1,0,0,1,0,0,0,1,1,1,0,1,0,1,1,0,0,0,0,0,0]         


'''####### empty arrays of zero ready to be filled #######'''

w_max_mean = np.zeros((2,np.size(dist)))
w_min_mean = np.zeros((2,np.size(dist)))
w_max_stderr = np.zeros((2,np.size(dist)))
w_min_stderr = np.zeros((2,np.size(dist)))

for k in range(np.size(file_n)):#range(1):#
    file_name = file_n[k] + ".csv"
    file_name1 = float(file_name)
    #file_name = float(file_name)
#    print(file_name)
    data = np.loadtxt(file_name1,comments='%',delimiter=',',usecols=[0,1],skiprows=0)
    time0 = data[:,0]
    volt0 = data[:,1]

    n_int = 10.#+ np.abs(k-15)
    t = np.zeros(np.array(np.size(t0)/n_int,dtype = int)-1);
    V = np.zeros(np.array(np.size(t0)/n_int,dtype = int)-1);

    for j in range(np.array(np.size(t0)/n_int,dtype = int)-1):
        t[j] = np.sum(t0[j*n_int:(j+1)*n_int-1])/n_int
        V[j] = np.sum(V0[j*n_int:(j+1)*n_int-1])/n_int

是什么导致这种情况?

1 个答案:

答案 0 :(得分:0)

[np.loadtxt] 1获取str作为第一个参数,而不是float。为什么要尝试将文件名转换为float?只需删除file_name1 = float(file_name)并替换

即可
data = np.loadtxt(file_name1,comments='%',delimiter=',',usecols=[0,1],skiprows=0) 

data = np.loadtxt(file_name, comments='%', delimiter=',', usecols=[0,1], skiprows=0) 

它应该都可以。