如何交换python(astropy.table)中两个表的行数?

How to swap the rows of two tables in python (astropy.table)?

我正在尝试交换两个 python 表的行,例如

    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

我希望它是

    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

我尝试使用此处给出的示例 Is there a standardized method to swap two variables in Python?,但其中 none 行得通可能是因为行类型:

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

例如

   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

即t2 不变。有解决办法吗? 我还尝试使用 Python Simple Swap Function 中给出的第一个解决方案,我将行更改为列表并交换它们,但它给出了断言错误。有人可以帮忙吗?

看起来您的代码已更改 t1[1],然后新值已覆盖 t2[1]。您需要制作 t1 的显式副本,更改副本,然后根据原始 t1 更改 t2。如果您必须通过多个步骤执行此操作,则每次都制作一个副本然后覆盖原始数据的副本可能更安全

import copy

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

t1[1], t2[1] = t2_copy[1], t1_copy[1]