Skip to main content
 首页 » 编程设计

python之将多个数据文件读入多个数组python

2024年10月25日8落叶无声

我是 Python 新手,在处理多个数据文件时遇到了问题。 我想将多个数据文件读取到多个数组中,例如我想将1c.txt中的数据读取到数组c1中,将2c.txt中的数据读取到c2中等等。我尝试了以下代码:

import numpy as np 
for i in range(1,15): 
     globals()['c%s' % i] = np.loadtxt(['%sc.txt' % i], usecols=(0,1,2)) 

但是提示IndexError: list index out of range,我把usecols=(0,1,2)改成了usecols=(0) 还是不行,所以我想一定是其他地方出了问题。

我还发现我无法将代码用作: ['c%s' % i] 获取变量名称为 c1、c2 等。我必须在 ['c%s' % i] 之前添加一个 globals(),但我不不知道为什么。

在线等待。非常感谢!

请您参考如下方法:

你应该使用 Python dict保存到数组的映射:

import numpy as np 
 
dict_of_arrays={} 
 
for i in range(1,15): 
    dict_of_arrays['c%i' % i]=np.array([1,2,3]) 
 
print dict_of_arrays   

打印:

{'c11': array([1, 2, 3]), 'c13': array([1, 2, 3]), 'c9': array([1, 2, 3]), 'c8': array([1, 2, 3]), 'c14': array([1, 2, 3]), 'c12': array([1, 2, 3]), 'c3': array([1, 2, 3]), 'c2': array([1, 2, 3]), 'c1': array([1, 2, 3]), 'c10': array([1, 2, 3]), 'c7': array([1, 2, 3]), 'c6': array([1, 2, 3]), 'c5': array([1, 2, 3]), 'c4': array([1, 2, 3])} 

然后访问一个单独的数组:dict_of_arrays['c11'] 以访问文件 c11 中的数据为例。