pandas数据框中的行重新排序子集(重新索引)

问题描述 投票:1回答:2

使用

import pandas as pd
import numpy as np

鉴于此数据框,

df = pd.DataFrame(np.array([[1, 2, 3],
                             [4, 5, 6],
                             [7, 8, 9],
                             [10, 11, 12],
                             [13, 14, 15],
                             [16, 17, 18],
                             [19, 20, 21]
                             ]),
                   columns=['a', 'b', 'c'])


Out[1]: 
    a   b   c
0   1   2   3
1   4   5   6
2   7   8   9
3  10  11  12
4  13  14  15
5  16  17  18
6  19  20  21

我想重新排序,然后将第2至5行放回原处,

2   7   8   9
3  10  11  12
4  13  14  15
5  16  17  18

如果子集中的顺序是[2,0,1,3],则期望的结果是,

Out[2]: 
    a   b   c
0   1   2   3
1   4   5   6
4  13  14  15
2   7   8   9
3  10  11  12
5  16  17  18
6  19  20  21

((我需要对不同顺序的不同子集执行此操作。这只是一个示例。)

我的尝试,

我的子集,

idx = [2,3,4,5]
idx2 = np.array(idx)

新订单

i = [2,0,1,3]

如果有,

df.iloc[idx].reindex(idx2[i])

我确实以正确的顺序获得了子集,然后,我认为以下应该起作用,

df.iloc[idx] = df.iloc[idx].reindex(idx2[i]).reset_index(drop=True)

但不是,因为它们双方都需要匹配索引。因此,我将需要在索引上设置偏移量,这有点麻烦。或进行此操作以忽略右侧的索引。有什么主意吗?

pandas dataframe rows assign
2个回答
1
投票

您可以使用基于输入列表的重排索引,然后在将原始索引中的重排索引过滤为2组之后将索引分离,然后使用np.r_np.r_来实现输出:

df.iloc[]

import more_itertools as mit
i = [2,0,1,3] #input list

rearranged_idx = df.index[2:6][i] #since you're interested in rows 2 to 5
i = [list(i) for i in 
     mit.consecutive_groups(df.index.difference(rearranged_idx,sort=False))]
# [[0, 1], [6]]
out = df.iloc[np.r_[i[0],rearranged_idx,i[-1]]]

1
投票

由于熊猫索引不可变,因此可以将其设置为数组,修改所需数组的一部分,然后按 a b c 0 1 2 3 1 4 5 6 4 13 14 15 2 7 8 9 3 10 11 12 5 16 17 18 6 19 20 21

reindex
© www.soinside.com 2019 - 2024. All rights reserved.