2

In the following dataframe, in each row, I want name1 value to be smaller values among name1 and name2.

data = {'name1': ['Jason', 'Molly', 'Tina', 'yuma', 'Amy'],
        'name2': ['Cochice', 'Pima', 'Santa', 'Maria', 'Yuma'],
        'val': [12, 22, 4, 9, 7],
        'db' : ['xx','yy', 'zz', 'mm', 'aa']}
df = DataFrame(data)
df


db  name1   name2   val
xx  Jason   Cochice 12
yy  Molly   Pima    22
zz  Tina    Santa   4
mm  yuma    Maria   9
aa  Amy Yuma    7

As far as I know sorting can be done by rows only. How to arrange values in this manner?

The expected output is:

db  name1   name2   val
xx  Cochice Jason   12
yy  Molly   Pima    22
zz  Santa   Tina    4
mm  Amy     Maricopa    9
aa  Amy     Yuma    7

1 Answer 1

2

You can use apply with sorted, but first set_index and last reset_index:

print (df.set_index('val').apply(sorted, axis=1).reset_index())
   val    name1  name2
0    2  Cochice  Jason
1    2    Molly   Pima
2    3    Santa   Tina
3    3      Amy  Maria
4    3      Amy   Yuma

Similar solution with np.sort:

print (df.set_index('val').apply(np.sort, axis=1).reset_index())
   val    name1  name2
0    2  Cochice  Jason
1    2    Molly   Pima
2    3    Santa   Tina
3    3      Amy  Maria
4    3      Amy   Yuma

If multiple columns use subset:

df[['name1','name2']] = df[['name1','name2']].apply(np.sort, axis=1)
print (df)
   db    name1  name2  val
0  xx  Cochice  Jason    2
1  yy    Molly   Pima    2
2  zz    Santa   Tina    3
3  mm      Amy  Maria    3
4  aa      Amy   Yuma    3
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfect but I think I was not very clear. I have other columns as well. I need this operation on only name1 and name2 keeping all other columns unchanged. Chaged the OP

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.