Home > Software design >  How to sort a list alphabetically taken from a DataFrame
How to sort a list alphabetically taken from a DataFrame

Time:11-07

I have following df....

symbol  changeInOI  latestOI  prevOI  volume  underlyingValue
ULTRACEMCO        2189     31832   29643   83044             6894
   DRREDDY        1399     32838   31439   25451             4520
BAJFINANCE        1305     69772   68467   73528             7212
    MARUTI         987     81983   80996   67356             9231
APOLLOHOSP         946     24054   23108   15873             4369
  BOSCHLTD         757      5376    4619    4559            16255
       LTI         576     11272   10696    5015             4811
       MRF         501      7734    7233    3132            91489
   PAGEIND         198      8480    8282    1747            49630
     DIXON         171      7718    7547    1868             4514
    HONAUT         162      2432    2270     733            40601
NAVINFLUOR         155      3119    2964    1002             4481
 INDIAMART          68      2954    2886    1397             4680
 NESTLEIND          54      8378    8324    1235            20422
ABBOTINDIA          38      1715    1677     490            19474
      ATUL          -4      2343    2347     747             8422
  SHREECEM        -275     17233   17508   12129            22838

Now I have a list of symbols from above df....

a = df.symbol.unique().tolist()

Now I want to sort above list of symbols alphabetically for which I tried....

a.sort()

but getting none as output. Why .sort() is not working here ???

CodePudding user response:

Read the Python documentation of the sort method of a list. Check the contents of a after calling .sort().

sort(*, key: None = ..., reverse: bool = ...) -> None
sort(*, key: (int) -> SupportsRichComparison, reverse: bool = ...) -> None

Sort the list in ascending order and return None. The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained). If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values. The reverse flag can be set to sort in descending order.

If you want the sorted list is a separate, new list, do:

sorted_list = sorted(a)
  • Related