使用模式在两个数据帧之间交换行

LOR*_*R13 1 python swap pandas

我有 2 个数据框,如下所示:

在每个数据帧中,值列中都有 1-2 的模式。(这些值对我的问题并不重要,只是为了演示模式)

df1 = {'idx': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
       'values': [20, 1000, 10001, 21, 1000, 1002, 22, 1003, 1007,23]}
df2 = {'idx': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
       'values': [1000, 21, 22, 1000, 22, 23, 1000, 20, 21, 1000]}
Run Code Online (Sandbox Code Playgroud)

我需要在两个数据帧之间交换行,以便结果是:

df_expected1 = {'idx': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
       'values': [20, 21, 22, 21, 22, 23, 22, 20, 21,23]}

df_expected2 = {'idx': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
       'values': [1000, 1000, 10001, 1000, 1000, 1002, 1000, 1003, 1007, 1000]}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 5

知道需要交换的索引来自3n-2,您可以制作 mask 然后使用numpy.where

m = df1["idx"].add(2).mod(3).eq(0)
s1 = np.where(m, df1["values"], df2["values"])
s2 = np.where(~m, df1["values"], df2["values"])

df1["values"] = s1
df2["values"] = s2
Run Code Online (Sandbox Code Playgroud)

输出:

   idx  values
0    1      20
1    2      21
2    3      22
3    4      21
4    5      22
5    6      23
6    7      22
7    8      20
8    9      21
9   10      23

   idx  values
0    1    1000
1    2    1000
2    3   10001
3    4    1000
4    5    1000
5    6    1002
6    7    1000
7    8    1003
8    9    1007
9   10    1000
Run Code Online (Sandbox Code Playgroud)