I'd like to know how to concatenate part of a string and sort it.
For example, i have a FIELD1 (string) and i should have the numbers of the string separated with ';' in the FIELD2. Only the numbers are repeated in the records. Moreover, i should sort the numbers ascending about their values.
How do I create an array string, in the field calculator of QGIS, to do this?
1 Answer 1
You need to create a new custom python expression in the Field Calculator to extract the numbers and sort them the way you want.
You can use the following expression:
from qgis.core import *
from qgis.gui import *
@qgsfunction(args='auto', group='Custom')
def extract_digits(text_field, feature, parent):
split_text = text_field.split()
num = [int(text) for text in split_text if text.isdigit()]
num_sort = sorted(num)
join_sort = ';'.join(['{}'.format (i,) for i in num_sort])
return join_sort
Then call the function from the custom expression, and use the field name that contains the street names:
Do not forget to select the new field in which the sorted digits will be saved.
The output will be like this:
Update
Based on your comment, I updated the script to take into consideration a semicolon (;)
that comes directly after a number. Please use the following code:
from qgis.core import *
from qgis.gui import *
@qgsfunction(args='auto', group='Custom')
def extract_digits(text_field, feature, parent):
split_text = text_field.split(';')
merge_text = ' '.join(split_text)
split_text = merge_text.split()
num = [int(text) for text in split_text if text.isdigit()]
num_sort = sorted(num)
join_sort = ';'.join(['{}'.format (i,) for i in num_sort])
return join_sort
-
Thank you very much! I'll try, i'm sure that it will works. If i already have the "FIELD2" with random numbers separated with ';' , how can i sort these, with ascending values, in a new field? Should i use array_sort? thanks..Mark– Mark2020年07月18日 11:12:26 +00:00Commented Jul 18, 2020 at 11:12
-
@Mark in your case use the above code to create custom expression. Then check Update existing field and select FIELD2, from the custom expression select extract_digits("FIELD1"). The numbers will be sorted in ascending order by the code.ahmadhanb– ahmadhanb2020年07月18日 11:45:47 +00:00Commented Jul 18, 2020 at 11:45
-
ahmadhanb the script doesn't work if there is the number before the ';' (for example ...;avenue 105;...). It doesn't return the number 105 in the list. Is it possible?Mark– Mark2020年07月25日 13:01:26 +00:00Commented Jul 25, 2020 at 13:01
-
@Mark Please use the updated code.ahmadhanb– ahmadhanb2020年07月27日 00:40:57 +00:00Commented Jul 27, 2020 at 0:40
-