Read Multiple Data File Into Multiple Arrays Python
I am new to Python, and I have a problem in dealing with multiple data files. I want to read multiple data files into multiple arrays, for example, I want to read data in 1c.txt to
Solution 1:
You should use a Python dict to hold a mapping to arrays:
import numpy as np
dict_of_arrays={}
for i inrange(1,15):
dict_of_arrays['c%i' % i]=np.array([1,2,3])
print dict_of_arrays
Prints:
{'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])}
Then access an individual array thus: dict_of_arrays['c11']
to access the data from file c11 as an example.
Solution 2:
Well, I can answer at least some of those questions.
I found I could not use the code as: ['c%s' % i] = np.loadtxt(['%sc.txt' % i]
That is because ['c%i' % i]
will give you a list of strings, not variables. By doing globals()[string]
you are accessing (assigning) to a dictionary (the globals() dictionary). I highly recommend NOT using globals()!
Do something like:
mydict = {}
for i in range(1,15):
mydict['c%i' % i] = np.loadtxt('c%i.txt' % i, usecols=(0,1,2))
I also notice that you are using %s
where you should be using %i
in your formatting, %s is for strings but your variable i
is an integer.
Post a Comment for "Read Multiple Data File Into Multiple Arrays Python"