-2

New to Python, I don't understand the outcome of the following operations. I read a table from a file using astropy.Table

data = Table.read(image_data_file, format='ascii')

Then I make a new identical table:

data2 = data

When a change an entry (or a whole column) in new table "data2", this is changed also in the original one "data".

data2['col2'] = 0 

Why is this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Giovanni
  • 1
  • 1

2 Answers2

1

Use data2 = data.copy() to make a copy instead of a reference to the same data.

Tom Aldcroft
  • 2,339
  • 1
  • 14
  • 16
0

This has been answered many times here but I don't remember under what name.

in python, if you do:

a = [1, 2, 3]
b = a
b.append(4)
b[2] = 5

at then end, a and b will both have the exact same data.

This is because b = a, so actually, python points both the variables to the same memory address behind the scene.

DevLounge
  • 8,313
  • 3
  • 31
  • 44
  • thanks: i was not able to find a similar question. But what surprised me is that the situaiton is different for calar values. I mean: x = 1 y = x y = y+1 at the end , x and y are different, so in this case the two variables are not poiting to the same address? – Giovanni Sep 26 '15 at 17:31
  • because y = x makes it point to the same address, but then y = y + 1 destroys the reference to x and this time takes the value of y and adds 1 to it (it works because y is of type int or float) – DevLounge Sep 26 '15 at 17:56