Python 对数据帧中的行子集重新排序(重新索引)
使用 考虑到这个数据帧Python 对数据帧中的行子集重新排序(重新索引),python,pandas,dataframe,rows,assign,Python,Pandas,Dataframe,Rows,Assign,使用 考虑到这个数据帧 import pandas as pd import numpy as np 我想重新排序并将第2到第5行放回原位 df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12],
import pandas as pd
import numpy as np
我想重新排序并将第2到第5行放回原位
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,0,1,3]
,则所需结果为
2 7 8 9
3 10 11 12
4 13 14 15
5 16 17 18
(我需要对不同顺序的不同子集执行此操作。这只是一个示例。)
我的尝试
我的子集
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[]
实现输出:
df.iloc[idx] = df.iloc[idx].reindex(idx2[i]).reset_index(drop=True)
由于索引是不可变的,您可以将其设置为数组,修改所需数组的部分,然后
reindex
:
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
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]
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