询问np.loadtext文件()功能

2024-09-27 07:31:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试使用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

有没有办法不用硬编码来使用np.loadtxt?你知道吗

谢谢


Tags: csvtheselfinfonumpy编码datareturn
1条回答
网友
1楼 · 发布于 2024-09-27 07:31:29

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

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

然后可以使用^{},它更强大:

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

dtype=None将自动确定每个列的数据类型。你知道吗

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')])

相关问题 更多 >

    热门问题