Sos
Sos

Reputation: 1949

Ordering dataframe columns row by row

I have a df that looks like this

df = pd.DataFrame({'A' : ['1','2','3','7'],
                   'B' : [7,6,5,4],
                   'C' : [5,8,7,1],
                   'v' : [1,9,9,8]})
df=df.set_index('A')
df

    B   C   v
A           
1   7   5   1
2   6   8   9
3   5   7   9
7   4   1   8

I'd like to sort it so that column B and C respectively show the lower and higher value of the two, i.e.

    B   C   v
A           
1   5   7   1
2   6   8   9
3   5   7   9
7   1   4   8

I can do this in a for loop that goes through each row, but I'm wondering if there is a better way to do it?

Upvotes: 0

Views: 44

Answers (1)

jezrael
jezrael

Reputation: 862601

If performance is important use numpy.sort with axis=1:

df[['B','C']] = np.sort(df[['B','C']], axis=1)
print (df)
   B  C  v
A         
1  5  7  1
2  6  8  9
3  5  7  9
7  1  4  8

Upvotes: 4

Related Questions