python – numpy genfromtxt转换器未知列数
发布时间:2020-12-20 11:34:53 所属栏目:Python 来源:网络整理
导读:我有几个数据数字文件,其中小数点分隔符是逗号.所以我使用lambda函数进行转换: import numpy as npdef decimal_converter(num_cols): conv = dict((col,lambda valstr: float(valstr.decode('utf-8').replace(',','.'))) for col in range(nb_cols)) retu
我有几个数据数字文件,其中小数点分隔符是逗号.所以我使用lambda函数进行转换:
import numpy as np def decimal_converter(num_cols): conv = dict((col,lambda valstr: float(valstr.decode('utf-8').replace(',','.'))) for col in range(nb_cols)) return conv data = np.genfromtxt("file.csv",converters = decimal_converter(3)) 文件中的数据是这样的: 0; 0,28321815; 0,5819178 1; 0,56868281; 0,85621369 2; 0,24022026; 0,53490058 3; 0,63641921; 0,0293904 4; 0,65585546; 0,55913776 这里有我的函数decimal_converter我需要指定我的文件包含的列数.通常我不需要指定numpy.genfromtxt文件中的列数,它需要它找到的所有列.即使使用转换器选项,我也希望保留此功能. 解决方法
由于genfromtxt()接受迭代器,您可以传递应用转换函数的迭代器,然后您可以避免转换器参数:
import numpy as np def conv(x): return x.replace(','.').encode() data = np.genfromtxt((conv(x) for x in open("test.txt")),delimiter=';') (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |