Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR 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
 
PREVIOUS NEXT
Tagged: #sort #column #numeric #text #data
ADD COMMENT
Topic
Name
1+8 =