I am trying to find out the counties that don't contain any stores in ArcGIS using python.
I have a point layer (representing the stores) and a polygon layer (counties). I have managed to write some code to find out the counties that DO contain the stores. The code is below.
import arcpy
arcpy.env.overwriteOutput = True
path="C:/Users/XARDAS/Documents/ArcGIS/Packages/Romania1000k_9E5B7FEC-6005-4D3A-81EA-E95FAACEF69E/v101/ro1mil.gdb"
arcpy.MakeFeatureLayer_management(path+"/Counties", "Counties_lyr")
arcpy.MakeFeatureLayer_management(path+"/Stores", "Stores_lyr")
arcpy.SelectLayerByAttribute_management("Stores_lyr", "NEW_SELECTION","Type=1")
arcpy.SelectLayerByLocation_management("Counties_lyr","INTERSECT","Stores_lyr",0,"NEW_SELECTION")
So this gives me the counties that have stores but I would like to somehow inverse the intersection for the program to give me the ones that don't have any stores. I have thought about just deleting the selected counties but I don't think that it would be too nice.
Since you have selected everything that you don't want selected, inverting (or switching) the selection will give you what you want. (ref help page)
Add this line at the end:
arcpy.SelectLayerByAttribute_management("Counties_lyr", "SWITCH_SELECTION")
The answer above works but SelectLayerByLocation allows you to invert the selection within the function:
arcpy.SelectLayerByLocation_management("Counties_lyr","INTERSECT","Stores_lyr",0,"NEW_SELECTION","INVERT")
Related
All,
I have been working on an index of all MTB trails worldwide. I'm a Python person so for all steps involved I try to use Python modules.
I was able to grab relations from the OSM overpass API like this:
from OSMPythonTools.overpass import Overpass
overpass = Overpass()
def fetch_relation_coords(relation):
rel = overpass.query('rel(%s); (._;>;); out;' % relation)
return rel
rel = fetch_relation_coords("6750628")
I'm choosing this particular relation (6750628) because it is one of several that is resulting in discontinuous (or otherwise erroneous) plots.
I process the "rel" object to get a pandas.DataFrame like this:
elements = pd.DataFrame(rel.toJSON()['elements'])
"elements" looks like this:
The Elements pandas.DataFrame contains rows of the types "relation" (1 in this case), several of the type "way" and many of the type "node". It was my understanding that I would use the "relation" row, "members" column to extract the order of the ways (which point to the nodes), and use that order to make a list of the latitudes and longitudes of the nodes (for later use in leaflet), in the correct order, that is, the order that leads to continuous path on a map.
However, that is not the case. For this particular relation, I end up with the following plot:
If we compare that with the way the relation is displayed on openstreetmap.org itself, we see that it goes wrong (focus on the middle, eastern part of the trail). I have many examples of this happening, although there are also a lot of relations that do display correctly.
So I was wondering, what am I missing? Are there nodes with tags that need to be ignored? I already tried several things, including leaving out nodes with any tags, this does not help. Somewhere my processing is wrong but I don't understand where.
You need to sort the ways inside the relation yourself. Only a few relation types require sorted members, for example some route relations such as route=bus and route=tram. Others may have sorted members, such as route=hiking, route=bicycle etc., but they don't require them. Various other relations, such as boundary relations (type=boundary), usually don't have sorted members.
I'm pretty sure there are already various tools for sorting relation members, obviously this includes the openstreetmap.org website where this relation is shown correctly. Unfortunately I'm not able to point you to these tools but I guess a little bit research will reveal others.
If I opt to just plot the different way on top of each other, I indeed get a continuous plot (index contains the indexes for all nodes per way):
In the Database I would have preferred to have the nodes sorted anyway because I could use them to make a GPX file on the fly. But I guess I did answer my own question with this approach, thank you #scai for tipping me into this direction.
You could have a look at shapely.ops.linemerge, which seems to be smart enough to chain multiple linestrings even if the directions are inconsistent. For example (adapted from here):
from shapely import geometry, ops
line_a = geometry.LineString([[0,0], [1,1]])
line_b = geometry.LineString([[1,0], [2,5], [1,1]]) # <- switch direction
line_c = geometry.LineString([[1,0], [2,0]])
multi_line = geometry.MultiLineString([line_a, line_b, line_c])
merged_line = ops.linemerge(multi_line)
print(merged_line)
# output:
LINESTRING (0 0, 1 1, 2 5, 1 0, 2 0)
Then you just need to make sure that the endpoints match exactly.
I am a final year undergraduate doing my dissertation. I am replicating Reagh's (2016) Mnemonic Similarity Task and am struggling with coding for the Spatial Task.
What I want to achieve is all stimuli coded '5' in my excel file to appear on the left hand side of the screen and all stimuli coded '10' to appear on the right. I've built the rest of my study via builderview and have tried multiple ways of coding this but haven't been successful. Sorry if this is a silly question but am very new to this and have watched and read many things to try and help me - any help at all would be appreciated :) I've added a link to a photo of my excel conditions file.
SpatialStudy.csv
If you have the data in a pandas dataframe, you can use the pivot method with columns='LeftRight' to reorganize the data so there is a column for each unique value within the Left right column.
For reading the file you could use pandas
and for printing a write should do
import pandas as pd
#reads the csv
df = pd.read_csv("yourfile")
#gets all of the ones with 5 on the leftright column
right = df.loc[df['LeftRight'] == 5]
#gets all of the ones with 10 on the leftright column
left = df.loc[df['LeftRight'] == 10]
# for the prinring part i dont know if you mean on the right of the output page or you want a black screen so this is just for the output page
sys.stdout.write("%-6s %-50s %-25s\n" % (right, left))
Insert a code component (from the "custom" component panel in the Builder interface). In its "Begin experiment" tab, insert something like this to map your variable's contents to a position on screen:
position_map = {5:-200, 10:200}
i.e. we have created a dictionary that will return the corresponding horizontal position when fed a value of either 5 or 10. Note that I've used arbitrary positions of -200 and 200 pixels. Replace with whatever values make sense for your stimulus and chosen units.
Then in the relevant stimulus component, put something like this in its "position" field, and set that field to update every repeat:
(position_map[LeftRight], 0)
PS in the future you might find it better to take queries like this to the dedicated support forum at https://discourse.psychopy.org. StackOverflow can be quite fussy about questions that aren't really programming-based.
I’m new to python, so I'm sorry if my question seems to be silly.
But, I'll be grateful if someone could help.
I'm writing a script in Maya Python.
I have a set of duplicated meshes. I need to select certain poly edges and convert them into curves.
I've managed to write the last part of converting the polyEdge to Curve, but struggling to write the wildcard selection.
I was thinking to write the following way:
list = [list of objects I want to get edges of]
for i in list:
pm.select()
Kind of like that,
But to be honest I don't know what I'm doing here.
I'd appreciate any help.
Thank you
here is an example
# list of your duplicates
myDuplicatedMeshes = ['pShpere1_dup']
# select your edges in the viewport for detecting which edges to transfer
edgeInputList = cmds.ls(sl=True)
# collect the edges ids
edgeIds = [i.split('.')[-1] for i in edgeInputList]
# loop into the duplicated
for dup in myDuplicatedMeshes:
# give the edge ids
targeted_edges = ['{}.{}'.format(dup, id) for id in edgeIds]
# convert to curve
curveBuilded = cmds.polyToCurve(targeted_edges, form=2, degree=3)
I am very new to programming and might have bitten off more than I can chew. I am trying to create a program that allows me to find the shortest route to visit all of the National Parks by importing a csv file containing the park names and distances between each park. Ideally, I would like it to prompt the user for which park they would like to start with and then run through the other parks to find the shortest distance (e.g. if you wanted to start with Yellowstone, it would find the closest park to Yellowstone, then the closest park to that park, etc., then add up all those distances, returning the total mileage and the order the parks were visited in) I think I need to be importing the csv file as a dictionary so I can use the park names as keys, but I'm not sure then how to work the keys into the algorithm. So far I have the following put together from my limited knowledge:
import csv
import numpy as np
distances = csv.DictReader(open("ds.csv"))
for row in distances:
print(row)
startingPark = input('Which park would you like to test?')
def NN(distanceArray, start):
path = [start]
cost = 0
N = A.shape[0]
mask = np.ones(N, dtype=bool)
mask[start] = False
for i in range(N-1):
last = path[-1]
next_ind = np.argmin(distanceArray[last][mask]) # find minimum of remaining locations
next_loc = np.arange(N)[mask][next_ind] # convert to original location
path.append(next_loc)
mask[next_loc] = False
cost += distanceArray[last, next_loc]
return path, cost
print (NN(distanceArray,0))
I know that I have to change all of the array stuff in the actual algorithm part of the code (that's just some code I was able to find through research on here that I am using as a starting point), but I am unsure of A: how to get it to actually use the input I give and B: how to make the algorithm work with the dictionary instead of with arrays that are input as part of the code itself. I've tried using the documentation and such, but it goes a bit over my head. Obviously I don't want anyone to just do it for me, but I'd appreciate any pointers or resources that people may have. I'm trying very hard to learn, but with no real guidance from anyone that knows what they're doing, I'm having a hard time.
Edit: Here is a sample of the data I have to work with. I pulled all of the distances from Google Maps and input them into a csv file. I think the x's I have in place might also be a problem and might need to be replaced with 0's or something similar, but I haven't gotten to handling that issue yet. (Sorry for not just uploading the picture, not enough rep to post one yet)
https://imgur.com/a/I4c1T
I feel like there is a simple solution to this but I am kinda new.
stat_input= input("Hello Mr. Jenner, what are you interested in tracking today?")
I use an input like this which later is used to call upon data and uses that data to calculate statistics and produce histogram charts / normal distributions.
It works quite nicely. Here are some examples where it is used.
cur.execute('SELECT {} FROM statdata'.format(stat_input))
np.array(stat_input).astype(np.float)
sigma = math.sqrt(np.var(stat_input))
So if I type threemonthdata it will pull the array of data from my database and use it . Its great. However, I have one small problem
I understand that threemonthdata refers to an array. Since I am creating charts, I want to use the input as the title so the chart title identifies what data I am drawing and using (as a reference in the future)
ax.set_title('stat_input')
This doesn't work
ax.set_title(' + stat_input + ')
Nor does this. I want the title to say Threemonthdata. But if I input twomonthdata I want it to say twomonthdata and not give me the array of numbers.
Any ideas?
I have never played with psycopg's cursor class. But, from what I can read, it appears that this one does the job for you of turning your string in place into a list whose name is the same as the referring string.
Thus what about defining another viariable to store the string before it is overriden ? As follows
stat_input_title = stat_input.capitalize()
cur.execute('SELECT {} FROM statdata'.format(stat_input))
Henceforth, stat_input_title and stat_input can be used together withouh conflicting.
ax.set_title(stat_input_title)
It looks like the issue you are facing is that you are passing the set_title() a string 'stat_input', and not the variable stat_input. You likely simply need to use:
ax.set_title(stat_input)