【问题标题】:how to fix: float() argument can be string or number, not 'map'如何解决:float() 参数可以是字符串或数字,而不是“地图”
【发布时间】:2019-09-10 19:25:40
【问题描述】:

这是我的简单代码:

我已尝试更改某些数据类型

@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' 

请帮我解决这个问题

【问题讨论】:

  • 您能告诉我们您要打开的文件是什么样的吗?同样在我看来,您需要“具体化”生成的地图列表。为了清楚起见,您最好将该行 (raw_data) 分解为多个步骤。

标签: python numpy typeerror


【解决方案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]

【讨论】:

    猜你喜欢
    • 2020-04-24
    • 2022-11-19
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2023-02-18
    • 2019-05-22
    • 2023-04-09
    相关资源
    最近更新 更多