21

For QGIS 3, QgsMapLayerRegistry's functionality has been moved to QgsProject. So, for iterating over map layers, you should use that structure: layers = QgsProject.instance().mapLayers() .mapLayers() returns a dictionary structured as {layer_x_id: layer_x, layer_y_id: layer_y, ....}. Then you can iterate over layers like: for layer_id, layer in layers....


20

var poly = /* color: #d63000 */ee.Geometry.Polygon( [[[-76.0803, 10.8656], [-76.0913, 7.7436], [-73.1909, 7.7545], [-73.3776, 9.4273], [-75.2124, 10.9304]]]) var start = ee.Date('2014-10-01'); var finish = ee.Date('2018-03-31'); var collection = ee.ImageCollection('COPERNICUS/S1_GRD') .filterDate(start, finish) .filter(ee.Filter....


16

For QGIS 2.6 here is the code to identify each layer and group them: #make the desired groups for layers toc = self.iface.legendInterface() root = QgsProject.instance().layerTreeRoot() group1 = root.insertGroup(0, "Group Point") group2 = root.insertGroup(1, "Group Line") group3 = root.insertGroup(2, "Group Polygon") #get the list of layers from registry ...


12

Look at the answer to Updating value in iterrow for pandas: The rows you get back from iterrows are copies that are no longer connected to the original data frame, so edits don't change your dataframe. Thankfully, because each item you get back from iterrows contains the current index, you can use that to access and edit the relevant row of the ...


8

Here is another solution that does not involve iterating through days, but maps through unique dates (after removing seconds, microseconds...) that appear in the image collection. It also adds the image date as the id as @erg asked in a commentary above. function mosaicByDate(imcol){ // imcol: An image collection // returns: An image collection ...


8

Is this code faster (tested on a 300 features memory layer) : layer = iface.activeLayer() # Get name and type of attributes in layer intfieldsnames = [i.name() for i in layer.fields() if i.type() in [QVariant.LongLong, QVariant.Int]] with edit(layer): prov = layer.dataProvider() new_fields = [QgsField(f"{a}d", QVariant.String) for a in ...


7

There is not an Iterate Fields tool in ModelBuilder. I can think of two possible workarounds: Modify the model to run as a Python script. Define a list of the fields you want to use, and define a loop to go through each one and execute the IDW/export functions. I would go with this one personally, but it would be (much) easier with some Python knowledge. ...


7

Yes, each Layer has a method called getSelectionSet(), which returns a list of selected OIDs for the layer. >>> for lyr in arcpy.mapping.ListLayers(mxd): ... if lyr.isFeatureLayer and lyr.getSelectionSet(): ... print 'clearing {} selected features for layer: "{}"'.format(len(lyr.getSelectionSet()), lyr.name) ... # clear ...


6

You are describing the exact functionality of Data-Driven Pages (DDP), a built-in feature of ArcGIS. You can implement them either in a Python script or in ArcMap. If you've never used them before, I'd experiment with them in ArcMap first to get an idea of what you can do with them. From the sound of it, you should be able to do what you need without getting ...


6

You can call r.mapcalc in for loop. In shell it could look like this: X=5 # initialize first map r.mapcalc "old = 10" # loop for I in `seq $X` do r.mapcalc "new = old + 10" --overwrite g.rename rast=new,old --overwrite done In shell command seq 5 creates a sequence 1, 2, 3, 4 , 5. Note that you shouldn't use r.mapcalc like this (read from and write ...


6

To do that is preferable to use a QgsRasterBlock object to get raster values and python GDAL module to write resulting raster values in a new raster. In this case you only need raster1. Complete code is: from osgeo import gdal, osr import numpy as np layer = iface.activeLayer() provider = layer.dataProvider() extent = provider.extent() rows = layer....


6

Found a solution, by making a list of the scene IDs from the imageCollection and iterating over the list. Then in a loop I import the individual images instead of mapping/iterating over the imageCollection. Probably a more efficient way to do this, but this gets the job done. # ========================================================================== # ...


6

You can use the Graphical Modeller (Processing menu) to build the desired process. Add as many layers as you like, add your grid, then switch tabs and add a clip-process for each vector-layer and set the output as final. Though it is a bit more work than simply running a batch process, it saves time if you want to/have to repeat the process. For ...


6

Furthermore it appears only 3 items are stored in the list which makes me assume the iteration is more complex than a literal iteration where all images are calculated one by one? You've got some of the idea. In Earth Engine, your JavaScript code is, by default, not at all involved in the substantial computation. Instead, it is executed to construct a data ...


6

In your script, calculate field will compute the values of group for ALL the row (or the selected rows if you used a layer) at each iteration. Therefore the GROUP values for all rows are overwritten by has the value of the last "code2012". Note that you could use "calculate field" only once to update the value of group based on the value of field. For a ...


6

In your code, polycent is always set the last polygon's centroid. So you must add centroids to a list. Change your code into that: polycents = [] # empty list for feature in layer.getFeatures(): geom = feature.geometry() # add centroid to the list polycents.append(geom.centroid().asPoint()) azimuths = [] count = layer.featureCount() i = 0 ...


6

I don't think you need recursive, it looks like you want subtotals for different categories of "DIST_KM" Does this give something close to want you expect: SELECT COUNT(*) as anzahl, SUM(FLUX) AS summe, ROUND(DIST_KM +0.5, 0) AS Dist_group FROM "flows_workday_GK5" GROUP BY ROUND(DIST_KM +0.5, 0) Edit: There will be gaps in the groups if the data is sparse ...


6

You can also use Refactor fields. Takes ~15 s for a feature class with 44.000 features with 15 integer fields: lyr = QgsProject.instance().mapLayersByName('sksNaturvardsavtal')[0] #List all fields current mapping (a list of dictionaries, one dict for each field) default_mapping = [{'expression':f.name(), 'length':f.length(), 'name':f.name(), 'precision':f....


5

Check that the layer is valid. If the layer, or the path is not valid qgis will no raise an error, it will return a QgsVectorLayer object where you can call the methods but with mostly no-op. layer = QgsVectorLayer(shapefile, 'borders', 'ogr') if not layer.isValid(): raise Exception('Layer is not valid') It will be probably a bad path. Also try to open ...


5

To get started with a Python script you can try code below. ListRasters will sort your rasters by name so if they are named like you say, it should work. Otherwise there are other ways of sorting the list. import arcpy from arcpy.sa import * from itertools import izip folder = r'C:\Test\Rasters' #Or geodatabase. Change to match your data. arcpy.env....


5

With RECURSIVE query, you have to do a generate_series (PostgreSQL function not supported by SQLite), which create you a number series from conf.start to conf.stop by conf.step. Then, retrieve this number and do what you want with, here your flow's summation SELECT. Here the Virtual Layers / SQLite / GeoPackage working code : -- number series WITH ...


5

As the exception states, SelectLayerByAttribute_management expects a layer (which is not the same thing as feature class -fc variable in your case, that you are passing, which is just the data) and you have to create one before passing into the def. If you use Make Feature Layer tool to create a layer just before SelectRandomByCount call and pass this layer ...


5

I don't know if it is possible using actual options in Modeler or Processing window, but you can make a script doing that. from qgis.PyQt.QtCore import QCoreApplication from qgis.core import (QgsProcessing, QgsFeatureSink, QgsProcessingAlgorithm, QgsProcessingParameterFeatureSource, ...


4

Assuming that layer is your polygon layer, you may use this code: for feature in layer.getFeatures(): bbox = feature.geometry().boundingBox() bbox_extent = '%f,%f,%f,%f' % (bbox.xMinimum(), bbox.xMaximum(), bbox.yMinimum(), bbox.yMaximum()) processing.runalg("qgis:regularpoints",bbox_extent,1000,0,False,True,outfile) and you will create a grid ...


4

Take a look at arcpy.ListFeatureClasses() and how that works in a `for loop. See the Code Sample at the bottom of that page. Then as you loop through the feature classes you just use your same code, with addLayer pointing at each feature class in the loop. arcpy.env.workspace = r"C:\Temp\Roads.gdb\MainSt" mxd = arcpy.mapping.MapDocument("CURRENT") df = ...


4

The SearchCursor will return geometries with the SHAPE@ token which can be used as extracting features etc.: SHAPE@ —A geometry object for the feature. import arcpy feature_class = r'C:\test.gdb\polygon' with arcpy.da.SearchCursor(feature_class,'SHAPE@') as cursor: for row in cursor: #do something with row[0] You can of course also return ...


4

The problem is in arcpy.CalculateField_management. It overwrite ALL of the field rows when you run it. Using selection will solve this problem but it may cause perfomance problems. To avoid them use update cursors.


4

As Mr Che and radouxju have said calculate field does all the rows, and that you should be using an update cursor but I would like to add that you're using an older style of cursor.. the arcpy.da cursors are far superior, here's an example: #----------------------------- camp= "GROUP" a= parameters[0].valueAsText arcpy.AddField_management(a, camp, "TEXT", ""...


4

Try using the object identifier (FID or OBJECTID field). If you divide it by 65000 and convert the result to integer (equivalent to floor), then you will have your groups. int(floor(!FID!/65000)) note that you could use ceil() instead of floor() if you prefer to start at 1 instead of 0.


4

In the case of len(new_df) == 1, since t is not defined in elif, you get the error. That means the first block of if never runs before you get the error. Even if the first block worked once, you would get the wrong result after all. Because t would be t coming from previous iteration, not from current iteration. In case of len(new_df) > 1, first block of ...


Only top voted, non community-wiki answers of a minimum length are eligible