使用
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)
,但不是,因为在两侧它们都需要匹配索引。因此,我将需要在索引上设置偏移量,这有点麻烦。或执行此操作以忽略右侧的索引。 有想法吗?
答案 0 :(得分:2)
您可以根据输入列表使用重新排列索引,然后将原始索引中的重新排列索引过滤为2组,然后将索引分离出来,然后使用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]]]
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
答案 1 :(得分:2)
由于熊猫索引不是可变的,因此可以将其设为数组,修改所需数组的一部分,然后reindex
:
idx = [2,3,4,5]
i = [2,0,1,3]
# pandas index to array
arr_idx = df.index.to_numpy()
# modify the order of the array
arr_idx[idx] = arr_idx[idx][i]
# reindex
df = df.reindex(arr_idx)
print (df)
a b c
0 1 2 3
1 4 5 6
4 7 8 9
2 10 11 12
3 13 14 15
5 16 17 18
6 19 20 21