Rearrange columns in python pandas

Viewed 205

I have a DataFrame with 105 columns.I want to bring the last column in the middle of a dataframe.How can i achieve that.

col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 col11 col12 col13 col14 col15 

The output should look like

col1 col2 col3 col4 col5 col6 col7 col15 col8 col9 col10 col11 col12 col13 col14

df.iloc[:,list(range(7))+ [-1]]

The above code works for the first 7 cols and the last column but i got stuck on how to get the remaining column

2 Answers

pop + insert

import pandas as pd
df = pd.DataFrame({f'c{i}': [i] for i in range(1,16)})

cname = df.columns[-1]
df.insert(int(len(df.columns)/2), cname, df.pop(cname))

print(df)
#   c1  c2  c3  c4  c5  c6  c7  c15  c8  c9  c10  c11  c12  c13  c14
#0   1   2   3   4   5   6   7   15   8   9   10   11   12   13   14

np.r_

You create a list of the .iloc indices to slice with. There's a bit of math to deal with whether there are an even or odd number of columns.

N = int(len(df.columns)/2)
r = len(df.columns)%2
idx = np.r_[0:N, -1, -N-r:-1]
#array([ 0,  1,  2,  3,  4,  5,  6, -1, -8, -7, -6, -5, -4, -3, -2])

df = df.iloc[:, idx]
#   c1  c2  c3  c4  c5  c6  c7  c15  c8  c9  c10  c11  c12  c13  c14
#0   1   2   3   4   5   6   7   15   8   9   10   11   12   13   14

One with index union:

df = pd.DataFrame(columns=range(16)).add_prefix('col')

mid = len(df.columns)//2
idx = df.columns[:mid].union(df.columns[[-1]]
                      .union(df.columns[mid:-1],sort=False),sort=False)
out = df[idx]

Empty DataFrame
Columns: [col0, col1, col2, col3, col4, col5, col6, col7, 
         col15, col8, col9, col10, col11, col12, col13, col14]
Index: []
Related