TransWikia.com

Filling a field with a random string from a list in QGIS

Geographic Information Systems Asked on July 28, 2021

I need to fill a field with false string data from a given list randomly. There are rand and randf functions generating random numbers. There is a similar (not identical) question: Updating attribute field with random string value. But it doesn’t meet my need. Also, the answer in that post does not work as expected.

How can I fill the field with a random string from a list, preferably using existing functions?

Pseudo-expression I need: randstr(['A', 'B', 'C']).

3 Answers

You can build the array, build a random index and extract its value

array('a','b','c')[rand(0,2)]

Correct answer by JGH on July 28, 2021

You can try an expression like this:

with_variable('stringlist',array('string_a','string_b','string_c'),
array_get(@stringlist,rand(0,array_length(@stringlist)-1)))

Explanation: First set up an array as variable, so you only have to build your lookup-array once. Next we pickup a random position from this array using array_get() combined with rand(). The minimum value is 0, as the array is 0 based. Because of that, we also need to remove 1 from array_length(), which is not 0 based, serving as maximum value.

Answered by MrXsquared on July 28, 2021

I'm not an expression expert. My solution uses a custom function.

Function definition:

from qgis.core import *
from qgis.gui import *
import random

@qgsfunction(args=-1, group='Custom')
def randstr(in_list, feature, parent):
    return random.choice(in_list)

Usage:

randstr('A', 'B', 'C')

Answered by Emma on July 28, 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