concat 切片数据帧保留原始序列顺序

concat sliced dataframes preserving original series order

我有三个列表,[1,4,3][2,5,6][9,8,7],它们指的是数据框的系列索引。我正在使用每个列表将数据帧分割成一个较小的数据帧以进行批量数据处理。处理后,我想将数据帧重新组合到原始数据帧中,同时保留列的顺序。

df_1 = df.iloc[:,list1]
#carry out preprocessing
df_2 = df.iloc[:,list2]
#carry out preprocessing
df_3 = df.iloc[:,list3]
#carry out preprocessing

#join the frames back together
frames = [df_1,df_2,df_3]
df = pd.concat(frames, axis = 1)

有没有一种简单的方法来连接并保留系列的原始顺序?即 [1,2,3,4,5,6,7,8,9]

我认为不是,需要 sort_index 来对列名进行排序:

df = pd.concat(frames, axis = 1).sort_index(axis=1)

如果要按索引位置排序:

L = list1 + list2 + list3
df1 = pd.concat(frames, axis = 1).reindex(columns=df.columns[sorted(L)])

或按 iloc 排序:

df_1 = df.iloc[:,sorted(list1)]
#carry out preprocessing
df_2 = df.iloc[:,sorted(list2)]
#carry out preprocessing
df_3 = df.iloc[:,sorted(list3)]
#carry out preprocessing

样本:

np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(5,10)), columns=list('EFGHIJABCD'))
print (df)
   E  F  G  H  I  J  A  B  C  D
0  8  8  3  7  7  0  4  2  5  2
1  2  2  1  0  8  4  0  9  6  2
2  4  1  5  3  4  4  3  7  1  1
3  7  7  0  2  9  9  3  2  5  8
4  1  0  7  6  2  0  8  2  5  1

list1 = [1,4,3]
list2 = [2,5,6]
list3 = [9,8,7]

df_1 = df.iloc[:,list1]
#carry out preprocessing
df_2 = df.iloc[:,list2]
#carry out preprocessing
df_3 = df.iloc[:,list3]
#carry out preprocessing

#join the frames back together
frames = [df_1,df_2,df_3]
L = list1 + list2 + list3

df1 = pd.concat(frames, axis = 1).reindex(columns=df.columns[sorted(L)])
print (df1)
   F  G  H  I  J  A  B  C  D
0  8  3  7  7  0  4  2  5  2
1  2  1  0  8  4  0  9  6  2
2  1  5  3  4  4  3  7  1  1
3  7  0  2  9  9  3  2  5  8
4  0  7  6  2  0  8  2  5  1

df2 = pd.concat(frames, axis = 1).sort_index(axis=1)
print (df2)
   A  B  C  D  F  G  H  I  J
0  4  2  5  2  8  3  7  7  0
1  0  9  6  2  2  1  0  8  4
2  3  7  1  1  1  5  3  4  4
3  3  2  5  8  7  0  2  9  9
4  8  2  5  1  0  7  6  2  0

编辑:

如果列名与列表中的值相同 L:

L.sort()
df = df[L]

或者:

df = df[sorted(L)]