0

I am trying to swap the rows of two python tables, e.g

    In [15]: print t2
     x    y    z  
    ---- ---- ----
     20.0 30.0 40.0
     50.0 60.0 70.0
     80.0 90.0 99.0

    In [16]: print t1
     a   b   c 
    --- --- ---
     1.0 2.0 3.0 
     3.0 4.0 5.0
     6.0 7.0 8.0

I want it to be

    In [15]: print t2
     x    y    z  
    ---- ---- ----
     20.0 30.0 40.0
     3.0 4.0 5.0
     80.0 90.0 99.0

    In [16]: print t1
     a   b   c 
    --- --- ---
     1.0 2.0 3.0 
     50.0 60.0 70.0
     6.0 7.0 8.0

I tried using the examples given here Is there a standardized method to swap two variables in Python?, but none of them are working probably because of the row type:

   In [19]: type(t1[1])
   Out[19]: astropy.table.row.Row

e.g.

   In [20]: t1[1],t2[1] = t2[1], t1[1]

   In [21]: print t1
    a    b    c  
   ---- ---- ----
    1.0  2.0  3.0
    50.0 60.0 70.0
    6.0  7.0  8.0

    In [22]: print t2
     x    y    z  
    ---- ---- ----
    20.0 30.0 40.0
    50.0 60.0 70.0
    80.0 90.0 99.0

i.e. t2 does not change. Is there a fix to it? I also tried using the first solution given in Python Simple Swap Function where I changed the row to a list and swapped them but it gives the assertion error. Can someone help please?

Community
  • 1
  • 1
nk_science
  • 23
  • 4

1 Answers1

0

Looks like your code has changed t1[1]and then the new value has overwritten t2[1]. You need to make an explicit copy of t1, change the copy and then alter t2 based on the original t1. If you have to do this with multiple steps, it might just be safer to make a copy of each and then overwrite the copied data from the original each time

import copy

t1_copy = copy.deepcopy(t1)
t2_copy = copy.deepcopy(t2)

t1[1], t2[1] = t2_copy[1], t1_copy[1]
Andrew
  • 1,072
  • 1
  • 7
  • 15