Oft-addattr.py

From Open Foris Wiki

Jump to: navigation, search

oft-addattr.py Adds one attribute in a shape file.

Usage: oft-addattr.py <shapefile> <JoinAttrName> <NewAttrName> <textfile>

Description:

  • oft-addattr.py reads a space separated text file and uses the first and second columns to construct a lookup table which is used to add a new attribute in an existing shapefile. Each time the value in the first column is found in the JoinAttributeName field of the shapefile, the value in the second column is added in the field NewAttrName.
  • In case the corresponding value is not present in the textfile, the NewAttrName value for that record becomes -9999.

Example:

  • Open your working directory using
cd /home/...
  • The first lines of the attribute table of landuse.shp look like this:
 1 red
 2 green
 3 orange
 5 pink
 6 red
 7 blue
 8 orange
 9 green
 10 orange


  • In this exercise we create a space separated text file as a lookup table. You can create it in any text editor, such as gedit or kate and save the file as lookup.txt in your working directory.

Note: The first column contains the ID linking the lookup table to your shapefile and the second column contains the values you want to add to the new column of your shapefile.

 1 11
 2 22
 3 33
 4 44
 5 55 
 6 66 
 8 88
 9 99 
 10 1000
  • Now run the script in the command line.

Each time the value in the first column of lookup.txt is found in the JoinAttributeName of the landuse.shp, field in our case called id. The value in the second column is added in the field NewAttrName, here called newcol.

oft-addattr.py landuse.shp id newcol lookup.txt 

  • Load landuse.shp in QGIS and look at your attribute table. You should now find the new column called newcol with it values.
  • Take a look at the ID 7. The newcol value in landuse.shp is -9999. This is due to the fact that there was no value 7 in the first column of the lookup table. In that case the corresponding value is not present in the lookuptable, therefore the newcol value for that record becomes -9999.


Attribute table of landuse.shp containing the new column called newcol with values.


How to change the data typ of the values in the attribute table in QGIS

Add plugin Table Manager:

1. Click on the top bar'Plugins' -> click 'Fetch Python Plugins'.
2. Type in the filter 'Manager' -> then you should find 'Table Manager - Manages the attribute table structure'.
3. Install it. Close and re-open QGIS.
4. On top bar click 'Plugin' -> click 'Manage Plugins' -> tick box for 'Table Manager'.
5. On top bar click 'Plugin' -> you should now see 'Table' somewhere under 'Manage Plugins', click it and the option 'Table Manager' can be chosen.
6. From there you can edit your attribute table, add a new colum and choose the data type.



Back to Open Foris Toolkit Main Page

Back to Tools & Exercises



Personal tools