I would like to be able to create numpy arrays based on a number that could change.
For example, say I have 50 text files containing a 2x2 set of numbers
I would like to load those 50 files as numpy arrays and use them later in the code. A sample of code may look like:
import load numpy as np
num = 50 #this could change based on different conditions
for i in arange(num):
data%d % i = np.loadtxt("datafromafile%d.txt" % i)
Is this something like this possible? Thanks
asked Dec 13, 2014 at 2:45
-
Are the arrays in those files all of the same shape (2x2) or can they differ?Oliver W.– Oliver W.2014年12月13日 18:12:18 +00:00Commented Dec 13, 2014 at 18:12
2 Answers 2
You can store them in a list:
data = list()
for i in arange(num):
data.append(np.loadtxt("datafromafile%d.txt" % i))
Then you can access each array with:
>>> data[0] + data[1] # sum of the first and second numpy array
answered Dec 13, 2014 at 2:57
1 Comment
getaglow
elyase, thank you, I have used your fix many times since you submitted. Sorry it took so long to let you know how helpful you were.
As a oneliner it would be:
NUM = 50
data = [np.loadtxt("datafromafile%d.txt" % value) for value in np.arange(NUM)]
or
FILES = ['file1', 'file2', 'file3']
data = {key: np.loadtxt(key) for key in FILES}
as a dict with the filename as key.
answered Dec 13, 2014 at 16:02
Comments
lang-py