Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Python sort dataframe by list

# sorts the dataframe so resulting order of ColumnName matches order in list
df = df.set_index(ColumnName).reindex(list_to_sort_by).reset_index()
Comment

pandas sort by list

# Convert Tm-column to category and in set the sorter as categories hierarchy
# Youc could also do both lines in one just appending the cat.set_categories()
df.Tm = df.Tm.astype("category")
df.Tm.cat.set_categories(sorter, inplace=True)

print(df.Tm)
Out[48]: 
0    CHH
1    VAN
2    TOT
3    OKC
4    DAL
Name: Tm, dtype: category
Categories (38, object): [TOT < ATL < BOS < BRK ... UTA < VAN < WAS < WSB]

df.sort_values(["Tm"])  ## 'sort' changed to 'sort_values'
Out[49]: 
   Age   G           Player   Tm  Year     id
2   22  60      Ratko Varda  TOT  2001  13950
0   27   6    Cedric Hunter  CHH  1991   2967
4   31  81  Adrian Caldwell  DAL  1997   6169
3   34  52       Ryan Bowen  OKC  2009   6141
1   25   7    Maurice Baker  VAN  2004   5335
Comment

PREVIOUS NEXT
Code Example
Python :: pop element from list python 
Python :: dynamic array logic in python use 
Python :: generating random numbers numpy 
Python :: python print an array 
Python :: python use cases 
Python :: python try except print error 
Python :: Requested runtime (Python-3.7.6) is not available for this stack (heroku-20). 
Python :: json diff python 
Python :: string template python 
Python :: python print font size 
Python :: how to read a file in python 
Python :: if elif and else in python 
Python :: python 3 string length 
Python :: print column name and index python 
Python :: python enum 
Python :: Python format() function uses. 
Python :: unzipping the value using zip() python 
Python :: Patch loop runner _run_once 
Python :: keras.utils.plot_model keeps telling me to install pydot and graphviz 
Python :: check if string has square brackets python 
Python :: select columns rsnge dataframe 
Python :: how to test webhook in python.py 
Python :: pygame download for python 3.10 
Python :: loop in coding 1.2 
Python :: save csv with today date pandas 
Python :: ploting bargraph with value_counts(with title x and y label and name angle) 
Python :: pytest handling muliple cases 
Python :: calendar range 
Python :: intersect and count in sql 
Python :: Collecting pipnev 
ADD CONTENT
Topic
Content
Source link
Name
6+9 =