1

In my code, I have loaded data to an array. While looping over the array, everytime the else is executed, the array values of the amat array get changed (only for those i's where the loop is executed).

That is, amat[i] before the for loop does not equal amat[i] after the for loop, for those i's where the else statement is executed.

Here's my code snippet.

amat = np.loadtxt(infl)
for i,yentry in enumerate(amat):
    depth = yentry[0]
    if depth < dhigh:
        if depth >= dlow:
            if bint == 1:
                mindepth = dlow
            matline += yentry
            count += 1
    else:
        avgmat = matline / float(count)
        bavg[bint,:] = avgmat
        depthfix = round((dlow + dhigh)/2,1)
        bavg[bint,0] = depthfix
        stringlist.append((' '.join(['%10.6f ']*len(avgmat))+'\n') % tuple(avgmat))
        avgmat = yentry
        matline = yentry
        bint += 1
        count = 1
        dlow = dhigh
        dhigh += step

What could be causing this? As you can see, I have no statements which should affect the value of amat. Yet, something is obviously going on...

I know it's hard to diagnose without the full code, but can anyone think of any issues that might be causing this? How can my array get modified without applying any operations to it?

1
  • Your code contains variables like matline and avgmat which don't seem to be defined before they're used. Can you provide a self-contained, runnable example, including a small data sample, that actually demonstrates the problem? Commented Aug 20, 2015 at 18:15

1 Answer 1

4

When you define:

matline = yentry

inside the else block and after you do:

matline += yentry

it is actually changing one row of amat. Because matline is a reference to yentry, which is a reference to one row of amat.

To prevent this you could break the reference by creating a copy:

matline = yentry.copy()
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Your solution fixed the problem. I don't fully understand though... The wrong values that amat is taking on are not contained within amat. It's as if it's getting changed with random numbers. Also, when do I have to use the .copy()? For example, should I say that depth = yentry[0].copy()? Should I use .copy() whenever I do an operation when using the for loop variables?
@you only have to copy when there is a chain of references that must be broken. If yentry is a 1D array, when you do yentry[0] you already get a float number stored in a new variable, in a new place of memory... so you don't have to copy

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.