gpt4 book ai didi

python - 连接切片数据帧保留原始系列顺序

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:39 25 4
gpt4 key购买 nike

我有三个列表, [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)]

关于python - 连接切片数据帧保留原始系列顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48522563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com