[英]Selecting non-consecutive and consecutive columns from a pandas dataframe
[英]Rearranging a non-consecutive order of columns in pandas dataframe
我有一個帶有n個(變量)列的pandas數據幀(結果)df,是使用其他兩個數據幀的合並生成的:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.