2

I have a dataframe and the first column contains id. How do I sort the first column when it contains alphanumeric data, such as:

id = ["6LDFTLL9", "N9RFERBG", "6RHSDD46", "6UVSCF4H", "7SKDEZWE", "5566FT6N","6VPZ4T5P", "EHYXE34N", "6P4EF7BB", "TT56GTN2", "6YYPH399" ]

Expected result is

id = ["5566FT6N", "6LDFTLL9", "6P4EF7BB", "6RHSDD46", "6UVSCF4H", "6VPZ4T5P", "6YYPH399", "7SKDEZWE", "EHYXE34N", "N9RFERBG", "TT56GTN2" ] 
Andy
  • 49,085
  • 60
  • 166
  • 233
  • 1
    Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful. – jezrael Apr 11 '17 at 13:30
  • expected result is id = ["5566FT6N","6LDFTLL9", "6P4EF7BB", "6RHSDD46", "6UVSCF4H","6VPZ4T5P","6YYPH399","7SKDEZWE", "EHYXE34N",,"N9RFERBG","TT56GTN2" ] –  Apr 11 '17 at 13:36

1 Answers1

1

You can utilize the .sort() method:

>>> id.sort()
['5566FT6N', '6LDFTLL9', '6P4EF7BB', '6RHSDD46', '6UVSCF4H', '6VPZ4T5P', '6YYPH399', '7SKDEZWE', 'EHYXE34N', 'N9RFERBG', 'TT56GTN2']

This will sort the list in place. If you don't want to change the original id list, you can utilize the sorted() method

>>> sorted(id)
['5566FT6N', '6LDFTLL9', '6P4EF7BB', '6RHSDD46', '6UVSCF4H', '6VPZ4T5P', '6YYPH399', '7SKDEZWE', 'EHYXE34N', 'N9RFERBG', 'TT56GTN2']
>>> id
['6LDFTLL9', 'N9RFERBG', '6RHSDD46', '6UVSCF4H', '7SKDEZWE', '5566FT6N', '6VPZ4T5P', 'EHYXE34N', '6P4EF7BB', 'TT56GTN2', '6YYPH399']

Notice, with this one, that id is unchanged.


For a DataFrame, you want to use sort_values().

df.sort_values(0, inplace=True)

0 is either the numerical index of your column or you can pass the column name (eg. id)

           0
5   5566FT6N
0   6LDFTLL9
8   6P4EF7BB
2   6RHSDD46
3   6UVSCF4H
6   6VPZ4T5P
10  6YYPH399
4   7SKDEZWE
7   EHYXE34N
1   N9RFERBG
9   TT56GTN2
Andy
  • 49,085
  • 60
  • 166
  • 233
  • Thank you for your answer. i have a dataframe. But the command sorted (df[íd'] ) is not successful –  Apr 11 '17 at 13:45
  • I've added an example on how to sort the column in a dataframe that should assist you. You will want to use `sort_values()` – Andy Apr 11 '17 at 13:54