Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

sort column with numeric and text data

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 :: write json to file python 
Python :: import random py 
Python :: tkinter gui grid and frame 
Python :: sort array python by column 
Python :: encrypt and decrypt python 
Python :: all alphabets 
Python :: store all files name in a folder python 
Python :: pandas object to float 
Python :: python column = sum of list of columns 
Python :: python code to plot pretty figures 
Python :: python path filename 
Python :: find duplicate in dataset python 
Python :: python3 return a list of indexes of a specific character in a string 
Python :: sqlalchemy check if database exists 
Python :: install python3 6 ubuntu 20 
Python :: python finite difference approximation backward difference 
Python :: python list methods 
Python :: how to remove duplicate files from folder with python 
Python :: getting pi in python 
Python :: natsort python pip install 
Python :: cv2 videocapture program for python 
Python :: how to swap tuple 
Python :: how to keep columns in pandas 
Python :: python split sentence into words 
Python :: win32api.mouse_event python 
Python :: how to stop python prompt 
Python :: pandas get date from datetime 
Python :: pandas transform date format? 
Python :: blackjack in python 
Python :: real time crypto prices python 
ADD CONTENT
Topic
Content
Source link
Name
6+3 =