Skip to main content
 首页 » 编程设计

python之关于 np.loadtext() 函数的查询

2025年05月04日12oomusou

我一直在尝试使用 NumPy 模块解析 CSV 文件,如下所示,我不得不对 dtype 进行硬编码,这可以是也见下文。

def FileR(self,FileName): 
    data = [('SecurityInfo', 'S64'), 
                 ('Date', 'S64'), 
                 ('Cost', 'float'), 
                 ('Yield', 'float'),]       
    return data 
 
def Gettheinfo(self): 
    the_info = np.loadtxt('the.csv', delimiter=',', skiprows = 1, dtype = self.FileR('the.csv')) 
    return the_info 

有没有办法不用硬编码data就可以使用np.loadtxt?

谢谢

请您参考如下方法:

我不知道你的文件是如何格式化的,但我假设它看起来像这样:

SecurityInfo,Date,Cost,Yield 
a string,another string,11.50,2110.3 
more,stuff,43.15,343 

然后你可以使用numpy.genfromtxt ,哪个更强大:

np.genfromtxt('abc.txt', delimiter=',', dtype=None, names=True) 

dtype=None 将自动确定每一列的 dtype。

names=True 将从文件的第一行读取字段名称。

例子:

>>> np.genfromtxt('abc.txt', delimiter=',', dtype=None, names=True) 
array([('a string', 'another string', 11.5, 2110.3), 
       ('more', 'stuff', 43.15, 343.0)],  
      dtype=[('SecurityInfo', 'S8'), ('Date', 'S14'), ('Cost', '<f8'), ('Yield', '<f8')])