Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to sort a column with mixed text number

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 py 
Python :: print a random word from list python 
Python :: TypeError: sequence item 0: expected str instance, int found 
Python :: q django 
Python :: python snake game 
Python :: pygame mouse pos 
Python :: pillow create image 
Python :: or statement django template 
Python :: Python - Drop row if two columns are NaN 
Python :: telethon invite to group 
Python :: python file name from absolute path 
Python :: how to get key and value from json array object in python 
Python :: import fashion mnist keras 
Python :: jupyter notebook set default directory 
Python :: log of number python 
Python :: python import ndjson data 
Python :: python remove all except numbers 
Python :: cprofile usage python 
Python :: python range backward 
Python :: jupyter notebook play audio 
Python :: binomial coefficient python 
Python :: explode dictionary pandas 
Python :: how to import matplotlib.pyplo in python 
Python :: how to make a window in tkinter 
Python :: athena connector python 
Python :: python number to letter 
Python :: python progress bar console 
Python :: print 2d array in python 
Python :: except as exception: 
Python :: python selenium full screen 
ADD CONTENT
Topic
Content
Source link
Name
9+6 =