I have a shape layer in qgis with blank attribute table. I want to fill attribute table with false data randomly. I successfully update the field with integer values using 'rand' expression. I am stuck at 'how to randomly fill string values.'

Suppose I have shape with drain 500 features. I want to enter values in drain_name field with values "ravi", "Sangpo","ganga",... etc.

Which expression should i use to update the drain name with random string value.


You may create your own custom python function through field calculator function editor to create random strings to populate a field:

  1. Click on the function editor tab within field cal
  2. Create new file and copy in code below
  3. Load the function

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

@qgsfunction(args='auto', group='Custom')
def myFun(value1, feature, parent):
    return randomword(10)

def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length))

Make a call under expression tab like and click Ok button to run:

| improve this answer | |
  • Hi, I am getting Null value after running it. – Sachin Dec 7 '16 at 6:02

Create a temporary attribute temp with rand( 1, 3). The higher number here has to be the number of the random values you want to use.

After that, fill the values in drain_name like this:

WHEN "temp" = 1 THEN 'ravi'
WHEN "temp" = 2 THEN 'Sangpo'
WHEN "temp" = 3 THEN 'ganga'

After that you can delete temp again.

| improve this answer | |
  • This is not a random string, you have to write them. And it's cumbersome to write 'words', especially if you have 500 features like he said. The other solution is much better. – etrimaille Aug 10 '16 at 19:19
  • I know what you mean, but my answer is supposed to show what you need to do in order to get "randomized words" instead of just scrambled up letters. Of course, that way you have to type them out first (or better, use a word list and some find/replace-magic). – karpfen Aug 10 '16 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.