我有一个字典,我需要转换为NumPy结构化数组.我正在使用arcpy函数NumPyArraytoTable,因此NumPy结构化数组是唯一可用的数据格式.
基于这个线程:从字典和这个线程写入numpy数组:如何将Python字典对象转换为numpy数组
我试过这个:
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
names = ['id','data']
formats = ['f8','f8']
dtype = dict(names = names, formats=formats)
array=numpy.array([[key,val] for (key,val) in result.iteritems()],dtype)
Run Code Online (Sandbox Code Playgroud)
但我一直在努力 expected a readable buffer object
下面的方法有效,但是很愚蠢,显然不适用于真实数据.我知道有一种更优雅的方法,我只是想不出来.
totable = numpy.array([[key,val] for (key,val) in result.iteritems()])
array=numpy.array([(totable[0,0],totable[0,1]),(totable[1,0],totable[1,1])],dtype)
Run Code Online (Sandbox Code Playgroud) 我有一个外部可执行文件,我试图从Python脚本运行.CMD可执行文件运行但不生成输出.可能在生成输出之前退出.有关如何延迟退出直到产生输出的任何建议?
import subprocess, sys
from subprocess import Popen, PIPE
exe_str = r"C:/Windows/System32/cmd C:/temp/calc.exe"
parent = subprocess.Popen(exe_str, stderr=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud) 我想编写一个简单的脚本来遍历文件夹中的所有文件,并将压缩文件(.zip)解压缩到同一个文件夹.对于这个项目,我有一个包含近100个压缩.las文件的文件夹,我希望能够轻松地批量解压缩它们.我尝试使用以下脚本
import os, zipfile
folder = 'D:/GISData/LiDAR/SomeFolder'
extension = ".zip"
for item in os.listdir(folder):
if item.endswith(extension):
zipfile.ZipFile.extract(item)
Run Code Online (Sandbox Code Playgroud)
但是,当我运行脚本时,我收到以下错误:
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 10, in <module>
extract = zipfile.ZipFile.extract(item)
TypeError: unbound method extract() must be called with ZipFile instance as first argument (got str instance instead)
Run Code Online (Sandbox Code Playgroud)
我正在使用python 2.7.5解释器.我查看了zipfile模块的文档(https://docs.python.org/2/library/zipfile.html#module-zipfile),我想了解我做错了什么.
我想在我看来,这个过程会是这样的:
但是,感谢Marcus,在实施建议时,我收到了另一个错误:
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 12, in <module>
zipfile.ZipFile(item).extract()
File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode]) …Run Code Online (Sandbox Code Playgroud) 我有一个脚本,该脚本从MSSQL数据库获取表,然后在ArcGIS中注册该表。它还使用其他几种arcpy方法。我试图将其与Flask结合使用,并开发了一个HTML界面,您可以在其中指定表。该脚本可以很好地在控制台上运行,但是,当在http://127.0.0.1:5000/上与Flask一起运行时,arcpy函数无法运行,则该应用程序将引发错误。
我正在使用本地python目录,因此在flask上导入arcpy时没有任何问题。因此,我能够使用pymssql函数并创建一个新表,但是当涉及到arcpy函数时,它不会引发错误,但是该表存在。我感觉用Flask运行arcpy有点问题,但是任何帮助将不胜感激。
(2)我在Django中尝试了相同的操作,但是遇到了相同的问题。
谢谢
class createGISLayer(FlaskForm):
tCreateLayer = SubmitField('Create GIS Layer')
Run Code Online (Sandbox Code Playgroud)
try:
cursor.execute(QueryCreate)
print ("Table Created.")
print(self.dbTablePath)
descTable = arcpy.Describe(self.dbTablePath)
except arcpy.ExecuteError:
print(arcpy.GetMessages())
Run Code Online (Sandbox Code Playgroud)
if formCreate.tCreateLayer.data and formCreate.validate_on_submit():
if myLayer is not None:
try:
print("Create GIS Layer")
myLayer.dashboardMain()
flash('GIS Layer created!', 'success')
except Exception as e:
print(e.message)
flash(e.message, 'danger')
Run Code Online (Sandbox Code Playgroud)
<!-- Create GIS Layer -->
<div class="content-section">
<form name='idCreateGISLayer' action="" method="POST">
<table style="height: auto; margin-left: auto; margin-right: auto; width: 600px;">
<tbody>
<tr>
{{ formCreate.hidden_tag() }}
<td …Run Code Online (Sandbox Code Playgroud) StackExchange上的第一个计时器.
我正在使用ArcGIS Server和Python.在尝试使用REST端点执行查询到地图服务时,我在JSON响应中获取esriFieldTypeDate字段的值为负时期.JSON响应如下所示:
{
"feature" :
{
"attributes" : {
"OBJECTID" : 11,
"BASIN" : "North Atlantic",
"TRACK_DATE" : -3739996800000,
}
,
"geometry" :
{
"paths" :
[
[
[-99.9999999999999, 30.0000000000001],
[-100.1, 30.5000000000001]
]
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
我所指的字段是上面JSON中的"TRACK_DATE".自epoch以来,ArcGIS Server返回的值始终以毫秒为单位.ArcGIS Server还提供HTML响应,同一查询的TRACK_DATE字段显示为"TRACK_DATE:1851/06/27 00:00:00 UTC".
因此,日期是在1900年之前,我理解Python内置的datetime模块无法处理1900年之前的日期.我使用的是32位Python v2.6.我试图通过使用将其转换为日期时间
datetime.datetime.utcfromtimestamp(float(-3739996800000)/1000)
然而,这失败了
ValueError: timestamp out of range for platform localtime()/gmtime() function
Run Code Online (Sandbox Code Playgroud)
如何在Python 2.6中使用负面和1900年前的时代?我看过类似的帖子,但找不到解释使用负面时代的帖子.
我正在编写一个 python 代码来读取多边形形状文件中的点并将它们保存在一个点形状文件中。所以首先我制作了一个文本文件并将点的 (x,y) 存储在该 .txt 文件中。然后我试图从文本文件中制作一个点形状文件,但它给出了一个错误。
这是代码(只是最后一部分):
creat point shape-file from text file
import fileinput
import string
import os
env.overwriteOutput=True
outpath="C:/roadpl"
newfc="newpoint.shp"
arcpy.CreateFeatureclass_management(outpath, newfc, "Point")
infile="C:/roadpl/roadL5.txt"
cursor=arcpy.da.InsertCursor(newfc, ["SHAPE@"])
array=arcpy.Array()
for line in fileinput.input(infile):
X, Y=string.split(line, " ")
array.add(arcpy.Point(X,Y))
cursor.insertRow([arcpy.Point(array)])
fileinput.close()
del cursor
Run Code Online (Sandbox Code Playgroud)
这是错误:
Traceback (most recent call last):
File "C:\Lab5\P_Code_L5", line 49, in <module>
point.X, point.Y = line.split()
File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\arcobjects\_base.py", line 87, in _set
return setattr(self._arc_object, attr_name, cval(val))
RuntimeError: …Run Code Online (Sandbox Code Playgroud) 我想提取两个下划线之间的字符串。“_”之间和两侧的字符数量会有所不同,但只会有两个下划线。带下划线的长字段是文本字段,要填写的字段是短整数。我已经能够解析下划线之前和之后的字符并填充要素类中的其他字段,但无法将中间部分放入新字段中。
示例1:102_1204_234324
我想返回“1204”
示例2:324423_1_342
我想返回“1”
我尝试了多种变体,我认为应该有效的一种是:
# Import system modules
import arcpy
#from arcpy import env
# Set environment settings
arcpy.env.workspace = "c:/temp/testing.gdb"
# Set local variables
inFeatures = "testFeature"
fieldName = "testField"
expression = "!parse_field!.split('_')[1::2]"
# Execute CalculateField
arcpy.CalculateField_management(inFeatures, fieldName, expression, "PYTHON", "")
Run Code Online (Sandbox Code Playgroud)
我认为会创建一个列表,然后返回列表中的每个第二个元素。然而要填写的字段(testField)仍然是空的。
谢谢-阿尔
我试图限制MATLAB中的光栅处理以仅包括shapefile边界内的区域,类似于ArcGIS Spatial Analyst函数使用蒙版的方式.以下是我正在使用的一些(可重现的)样本数据:
这是我用来计算NDVI的MATLAB脚本:
file = 'C:\path\to\doi1m2011_41111h4nw_usda.tif';
[I R] = geotiffread(file);
outputdir = 'C:\output\'
% Calculate NDVI
NIR = im2single(I(:,:,4));
red = im2single(I(:,:,1));
ndvi = (NIR - red) ./ (NIR + red);
double(ndvi);
imshow(ndvi,'DisplayRange',[-1 1]);
% Stretch to 0 - 255 and convert to 8-bit unsigned integer
ndvi = floor((ndvi + 1) * 128); % [-1 1] -> [0 256]
ndvi(ndvi < 0) = 0; % not really necessary, just …Run Code Online (Sandbox Code Playgroud) 我在使用 zipfile.Zipfile() 函数时遇到问题。它正确压缩我的文件,但在输出 zip 文件中包含我不想要的额外文件夹。它确实将我想要的所有文件放入 .zip 中,但默认情况下似乎添加了写入 .zip 文件中的文件的最后几个目录。有什么办法可以排除这些文件夹吗?这是我的代码:
import arcpy, os
from os import path as p
import zipfile
arcpy.overwriteOutput = True
def ZipShapes(path, out_path):
arcpy.env.workspace = path
shapes = arcpy.ListFeatureClasses()
# iterate through list of shapefiles
for shape in shapes:
name = p.splitext(shape)[0]
print name
zip_path = p.join(out_path, name + '.zip')
zip = zipfile.ZipFile(zip_path, 'w')
zip.write(p.join(path,shape))
for f in arcpy.ListFiles('%s*' %name):
if not f.endswith('.shp'):
zip.write(p.join(path,f))
print 'All files written to %s' %zip_path
zip.close()
if __name__ == '__main__':
path …Run Code Online (Sandbox Code Playgroud) 我已经检查http://www.lfd.uci.edu/~gohlke/pythonlibs/,http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//003m00000002000000.htm和https://pypi.python.org/pypi/pygeoif/0.4.1
这些逻辑位置都不能下载arcpy进行安装.我也试过Pip install arcpy.什么都行不通.