如何解决:float()参数可以是字符串或数字,而不是'map'

时间:2019-04-21 05:44:35

标签: python numpy typeerror

这是我的简单代码:

我尝试更改某些数据类型

@staticmethod
def load_from_file(filename, size_fit = 50):
    '''
    Loads the signal data from a file.
    filename: indicates the path of the file.
    size_fit: is the final number of sample axes will have.
    It uses linear interpolation to increase or decrease
    the number of samples.
    '''
    #Load the signal data from the file as a list
    #It skips the first and the last line and converts each number into an int
    data_raw = list(map(lambda x: int(x), i.split(" ")[1:-1]) for i in open(filename))
    #Convert the data into floats
    data = np.array(data_raw).astype(float)
    #Standardize the data by scaling it
    data_norm = scale(data)

并抛出错误:

data=np.array(data_raw).astype(float)
float() argument must be 'string' or 'number', not 'map' 

请帮助我解决此问题

1 个答案:

答案 0 :(得分:1)

您正在制作map对象的列表。尝试使用此列表理解:

data_raw = [[int(x) for x in i.split()[1:-1]] for i in open(filename)]

split默认为在空白处分割,因此不需要该参数。另外,考虑使用with来正确关闭文件:

with open(filename) as infile:
    data_raw = [[int(x) for x in i.split()[1:-1]] for i in infile]

在旁注中,numpy在您进行astype时会为您将字符串转换为数字,因此您可以轻松完成

with open(filename) as infile:
    data_raw = [i.split()[1:-1] for i in infile]