0

I have a loop which generates an array from a text file. Every time it passes through the loop I want it to add the new array to the old one but I'm not sure how to do this. For example:

loop=np.arange(1,50)
for arg in loop:
   str(arg)
   a=np.genfromtxt('dir/'+arg+'.txt').T[0]
total=a+a+a #I know this line is wrong

How do I get total to be the total of every a over the array loop.

2 Answers 2

1

Do the arrays you get from the text have a fixed length? If yes, reading the first array and then doing in-place summation should work:

a = np.genfromtxt('dir1.txt').T[0]

loop=np.arange(2, 50)
for arg in loop:
    str(arg)
    a += np.genfromtxt('dir'+arg+'.txt').T[0]

If your arrays have different lengths weird problems might happen when numpy tries to guess how to do the additions.

Sign up to request clarification or add additional context in comments.

Comments

1

If you just want to add the arrays you get while reading in a loop can't you add the array to total each time in the loop:

loop=np.arange(1,50)
total = []
for arg in loop:
   str(arg)
   a=np.genfromtxt('dir/'+arg+'.txt').T[0]
   total+=a (or total.append(a))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.