Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

sorting pandas dataframe like excel

df =pd.DataFrame([['Levy','SCOW/W 1585'],['Nicholson','693'],
                  ['Cann','A.5.2152'],['Ling','1601'],['Carlsson','PC11'],
                  ['Mohammed','1'],['Lam','1601']]
                ,columns=['Name','Code'])
df
	Name		Code
0	Levy		SCOW/W 1585
1	Nicholson	693
2	Cann		A.5.2152
3	Ling		1601
4	Carlsson	PC11
5	Mohammed	1
6	Lam			1601
# First, we create a key_colum in which we convert string into integer for numbers
# and give NaN value to text code
key_column = pd.to_numeric(df['Code'],errors='coerce')
df.insert(2,'key_column',key_column)
df

	Name		Code		 key_column
0	Levy		SCOW/W 1585	 NaN
1	Nicholson	693			 693.0
2	Cann		A.5.2152	 NaN
3	Ling		1601		 1601.0
4	Carlsson	PC11		 NaN
5	Mohammed	1			 1.0
6	Lam			1601		 1601.0
# then, we sort by key_column, at first  then by Code column.
df.sort_values(['key_column','Code'],inplace=True)
df
	Name		Code		 key_column
5	Mohammed	1			 1.0
1	Nicholson	693			 693.0
3	Ling		1601		 1601.0
6	Lam			1601		 1601.0
2	Cann		A.5.2152	 NaN
4	Carlsson	PC11		 NaN
0	Levy		SCOW/W 1585	 NaN
# After we done the job we drop the key_column and reset the index
df.drop('key_column', axis=1, inplace =True)
df.reset_index(inplace=True,drop=True)
df
	Name		Code
0	Mohammed	1
1	Nicholson	693
2	Ling		1601
3	Lam			1601
4	Cann		A.5.2152
5	Carlsson	PC11
6	Levy		SCOW/W 1585
Comment

PREVIOUS NEXT
Code Example
Python :: print random word python 
Python :: random py 
Python :: web server python 
Python :: python overwrite print on same line 
Python :: decrypt python code 
Python :: download pdf using python 
Python :: run sql query on pandas dataframe 
Python :: add time delta pytohn 
Python :: dataframe to dictionary with one column as key 
Python :: convert torch to numpy 
Python :: python basename 
Python :: python image plot 
Python :: first day of the month python 
Python :: jupyter notebook change default directory 
Python :: how to install python 3.6 ubuntu 
Python :: python backward difference 
Python :: list methods python 
Python :: cprofile implementation 
Python :: print() in python 
Python :: openpyxl add worksheet 
Python :: create a new file in python 3 
Python :: how to get a row from a dataframe in python 
Python :: python print do not use scientific notation 
Python :: urlencode python 
Python :: spyder 3.3.6 requires pyqtwebengine<5.13; python_version = "3", which is not installed. 
Python :: python get nth letter of alphabet 
Python :: numpy how to calculate variance 
Python :: pandas summarize all columns 
Python :: drop rows with null date in pandas 
Python :: swapcase 
ADD CONTENT
Topic
Content
Source link
Name
5+1 =