gpt4 book ai didi

python - 重新排列 pandas 数据框中不连续的列顺序

转载 作者:行者123 更新时间:2023-12-01 04:13:44 24 4
gpt4 key购买 nike

我有一个 pandas 数据框(结果) df ,其中包含 n 个(变量)列,是我使用其他两个数据框的合并生成的:

result1 = df1.merge(df2, on='ID', how='left')

result1 数据帧预计具有可变的列数(这是较大脚本的一部分)。我想以最后两列连续第二列和第三列的方式排列列,然后所有剩余的列将跟随(而第一列保留为第一列)。如果知道 result1 有 6 列,那么我可以使用:

result2=result1.iloc[:,[0,4,5,1,2,3]] #this works fine. 

但是,我需要 1,2,3 采用范围格式,因为为每个 df 输入全部数字是不切实际的。所以,我想到使用:

result2=result1.iloc[:,[0,len(result1.columns), len(result1.columns)-1, 1:len(result1.columns-2]]
#Assuming 6 columns : 0, 5 , 4 , 1, 2, 3

这将是理想的方式,但这会产生语法错误。有什么建议可以解决这个问题吗?

最佳答案

我不使用切片语法,而是构建一个列表并使用它:

>>> df
0 1 2 3 4 5
0 0 1 2 3 4 5
1 0 1 2 3 4 5
2 0 1 2 3 4 5
3 0 1 2 3 4 5
4 0 1 2 3 4 5
>>> ncol = len(df.columns)
>>> df.iloc[:,[0, ncol-1, ncol-2] + list(range(1,ncol-2))]
0 5 4 1 2 3
0 0 5 4 1 2 3
1 0 5 4 1 2 3
2 0 5 4 1 2 3
3 0 5 4 1 2 3
4 0 5 4 1 2 3

关于python - 重新排列 pandas 数据框中不连续的列顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34559396/

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