How can i arrange columns as per condition?


#1

My data set is
S1 S2 S3 S4
1 4 7 20
2 6 8 21
3 9 10 30

and i convert data as per condition that
sort as per maximum difference value between each column value

data after the condition should be like this

S4 S2 S3 S1
20 4 7 1
21 6 8 2
30 9 10 3

explanation:
the difference between max and min value
for S4 is 30 - 20 = 10,
for S2 is 9-4 = 5
for S3 is 10-7 = 3
for S1 is 3-1 =2
and the columns are sorted as per the difference value of max and min.


#2

Hey @rahulsemwal10 ,

I am assuming that you are using python pandas. I have created the data frame df as follows
15

1. find rank of columns based on (max - min) value

col_rank = ((df.max() - df.min()).sort_values(ascending=False)).index
col_rank = list(col_rank)

2. Access the data frame in that order

df[col_rank]

04

Hope this helps,
Sanad :slight_smile:


#3

Hey @mohdsanadzakirizvi, thanks for answer. but i am working on R and solved problem by input

setNames(df[order(sapply(df, function(i) max(i)-min(i)), decreasing = TRUE)], paste0(‘column’,seq_along(df)))

this helped me to solved my problem.


#4

Hey @rahulsemwal10,

Nice! One thing that is pretty interesting is the logic is almost same, only the implementation is different based on language. Whatever you have done, I have done the same but in the python way :slight_smile: