TransWikia.com

Concatenating part of string and sorting it using QGIS

Geographic Information Systems Asked on September 25, 2021

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.

enter image description here

enter image description here

How do I create an array string, in the field calculator of QGIS, to do this?

One Answer

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

enter image description here

Then call the function from the custom expression, and use the field name that contains the street names:

enter image description here

Do not forget to select the new field in which the sorted digits will be saved.

The output will be like this:

enter image description here

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

Correct answer by ahmadhanb on September 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP