How Does One Reorder Columns in a Data Frame

pandas how to swap or reorder columns

Two column Swapping

cols = list(df.columns)
a, b = cols.index('LastName'), cols.index('MiddleName')
cols[b], cols[a] = cols[a], cols[b]
df = df[cols]

Reorder column Swapping (2 swaps)

cols = list(df.columns)
a, b, c, d = cols.index('LastName'), cols.index('MiddleName'), cols.index('Contact'), cols.index('EmployeeID')
cols[a], cols[b], cols[c], cols[d] = cols[b], cols[a], cols[d], cols[c]
df = df[cols]

Swapping Multiple

Now it comes down to how you can play with list slices -

cols = list(df.columns)
cols = cols[1::2] + cols[::2]
df = df[cols]

Is it possible to reorder columns in a data frame so that ABCDE is reordered to ABDCE by specifying to move D to between B and C?

Try the following function.

Argument swap is the names of the 3 columns before reordering them.

reorder_df_cols <- function(x, swap){
i_swap <- match(swap, names(x))
tmp1 <- x[seq_len(i_swap[1])]
vars <- x[rev(i_swap[-1])]
tmp2 <- x[-c(seq_len(i_swap[1]), i_swap[-1])]
cbind(tmp1, vars, tmp2)
}

data(mtcars, package = "datasets")

swap <- c("disp", "hp", "gear")
colnames(reorder_df_cols(mtcars, swap))
# [1] "mpg" "cyl" "disp" "gear" "hp" "drat" "wt" "qsec" "vs"
#[10] "am" "carb"

How to rearrange Pandas column sequence?

def _col_seq_set(df, col_list, seq_list):
''' set dataframe 'df' col_list's sequence by seq_list '''
col_not_in_col_list = [x for x in list(df.columns) if x not in col_list]
for i in range(len(col_list)):
col_not_in_col_list.insert(seq_list[i], col_list[i])

return df[col_not_in_col_list]
DataFrame.col_seq_set = _col_seq_set

Set order of columns in pandas dataframe

Just select the order yourself by typing in the column names. Note the double brackets:

frame = frame[['column I want first', 'column I want second'...etc.]]

Re-order Columns In A Data Frame Depending On Conditions Of Values

We have to handle the positive and negative values seperately. One way is take sum of the columns , then using sort_values , we can adjust the ordering:

a = df.sum().sort_values(ascending=False)
b = pd.concat((a[a.gt(0)],a[a.lt(0)].sort_values(),a[a.eq(0)]))
out = df.reindex(columns=b.index)

print(out)

C A B D
0 0 0 0 0
1 1 0 -1 0
2 1 1 -1 0
3 1 1 -1 0

Reorder columns of a dataframe based on max length of columns

try via assign()+sort_values()+drop():

the idea here is to typecast whole dataframe to string(for getting the max length your original dtypes in dataframe remains same) and then calculate string length of each column and find the max number of length and sort according to it and after sorting drop that column:

df=(df.assign(s=df.astype(str).applymap(len).max(axis=1))
.sort_values('s',ignore_index=True,ascending=False).drop(columns='s'))

OR

as suggested by @mozway:

df=df.loc[df.astype(str).applymap(len).max(axis=1).sort_values(ascending=False).index]

OR

Another possible way is to reindex the index after sorting:

df=df.reindex(df.astype(str).applymap(len).max(axis=1).sort_values(ascending=False).index)


Related Topics



Leave a reply



Submit