在大 pandas 数据帧中重新排列不连续的列数 [英] Rearranging a non-consecutive order of columns in pandas dataframe

查看:98
本文介绍了在大 pandas 数据帧中重新排列不连续的列数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框(结果)df与n(可变)列,我使用两个其他数据帧的合并生成:

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

result1数据框预计有一列变量(这是一个较大的脚本的一部分)。我想以最后2列连续排列的方式安排列,则所有剩余的列都将跟随(而第一列保持为第一列)。如果result1已知有6列,那么我可以使用:

  result2 = result1.iloc [:,[0,4 ,5,1,2,3]]#这工作正常。 

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

  result2 = result1.iloc [:,[0,len(result1.columns),len (result1.columns)-1,1:len(result1.columns-2]] 
#Assuming 6列: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


I have a pandas data frame (result) df with n (variable) columns that I generated using the merge of two other data frames:

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

result1 dataframe is expected to have a variable # of columns (this is part of a larger script). i want to arrange the columns in a way that the last 2 columns will be the second and third consecutively, then all the remaining columns will follow (while the first column stays as first column). If result1 is known to have 6 columns, then i could use:

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

BUT, i need the 1,2,3 to be in a range format as it is not practical to enter the whole of the numbers for each df. So, i thought of using:

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

That would be the idea way but this is creating syntax errors. Any suggestions to fix this?

解决方案

Instead of using slicing syntax, I'd just build a list and use that:

>>> 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

这篇关于在大 pandas 数据帧中重新排列不连续的列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆