【问题标题】:Python: How can I compare integer data in numpy array to integer data in another numpy array and read the results into a .txt file?Python:如何将 numpy 数组中的整数数据与另一个 numpy 数组中的整数数据进行比较,并将结果读入 .txt 文件?
【发布时间】:2017-09-03 23:39:41
【问题描述】:

我有动物位置(X、Y、Z)数据和树数据(X、Y、Z)。我需要提取在动物位置周围发生的所有 XYZ 树输入 - 所以我需要将包含 xyz 动物位置的 numpy 数组与包含同一区域中树木的 x y z 点位置的 numpy 数组进行比较。我想将所有 xyz 树拉到点的 4 个单位半径内,并编写了一个函数来做到这一点。但它实际上并不仅仅拉动动物位置周围的树木。它只是打印所有可能的树。如何仅拉动动物点周围的树木,然后将它们放入可以在另一个程序中使用的 .txt 文件中?我是编程新手,非常感谢我能得到的任何帮助。

以下是我的#descriptions 代码:

#using array instead of dataframe 
import numpy as np
from laspy.file import File

#load and consolidate Veg Point Coordinates into  one array
VegList = sorted(glob.glob('/Users/sophiathompson/Desktop/copys/Clips/*.las'))
VegListCoords = []
for f in VegList:
    print(f)
    Veg= File(filename = f, mode = "r")  # Open the file # Eventually, this     will need to be the actual .laz files
    VegListCoords.append(np.vstack((Veg.x, Veg.y, Veg.z)).transpose())
    print (VegListCoords)
    XYZVegComplete = np.concatenate((VegListCoords), axis = 0)

#Load animal point locations (x, y, z .csv file) from clip 240967 into array
Animal240967 =   np.loadtxt(fname='/Users/ST/Desktop/copys/CatTXTfiles/240967_CatsFt.csv', delimiter =',') 

#Use to find all vegetation heights in a 4 unit diameter of each animal    point (animalx, animaly). #'d out lines of code are my attempts to make something work 
def near_Animal(animalx, animaly):
    for x, y, z in XYZVegComplete:
        r=2 #xy coordinates in ft
        PointsNearAnml = []
        if (x-animalx)**2 + (y-animaly)**2 >= r**2:
            PracticeTxt=open("/Users/ST/Desktop/practicefilecreate.txt", "w") 
            print (x, y, z)
            #print (x, y, z) >> PracticeTxt, x, y, z
            #PracticeTxt.write('%d %d %d \n' % Points)
            #PracticeTxt.write('%d %d %d \n' % x y z)
            #Points= (x, y, z)
            #with open("/Users/sophiathompson/Desktop/practicefilecreate.txt", "w") as PracticeTxt:
            #print >> PracticeTxt, Points
            #PracticeTxt.close
#Use to call near_Animal: gather Veg Points based on proximity to animal        points (using arrays)- 
for animalx, animaly in Animal240967:
    near_Animal(animalx, animaly)

【问题讨论】:

  • 使用您提供的代码并不容易。考虑创建一个Minimum, Complete, and Verifiable Example,具有代表性示例数据和预期输出。这样,您将更有可能更快地获得更好的答案。

标签: python arrays python-3.x numpy compare


【解决方案1】:

您实际上需要两种不同的功能,具体取决于您是在一组内还是在两组之间进行测量。这是一个兼具两者的功能,以及对它的作用的一些解释:

from scipy.spatial.distance import pdist, cdist
def near_fn(*args, dist = 2., outfile = "practicefilecreate.txt"):  
    if len(args) == 1:  #within a set, i.e. `Animal240967`
        coords = args[0]
        i, j = np.triu_indices(coords.size, 1)
        mask = pdist(coords, 'euclidean') < dist
        k = np.unique(np.r_[i[mask], j[mask]])
        np.savetxt(coords[k], outfile, delimiter = ',') #or whatever you want
    elif len(args) == 2: # between sets i.e. `XYZVegComplete` and `Animal240967`
        coords_ind, coords_dep = args
        k = np.any(cdist(coords_ind, coords_dep, 'euclidean') < dist, axis = 1)
        np.savetxt(coords_ind[k], outfile, delimiter = ',') #or whatever you want
    else:
        assert False, "Too many inputs"

这是做什么的:

  1. pdist 求集合元素之间的距离,但只求值的右上角(因为a-&gt;b 之间的距离与b-&gt;a 相同,a-&gt; 之间的距离为总是0)。这是一个一维数组,对应于triu_indices 给出的位置。找到小于阈值 (pdist &lt; dist) 的距离,将其映射到索引 (k = i[...]) 并将对应于这些索引的坐标写入磁盘 (np.savetxt(coords[k] . . . ))

  2. cdist 以二维矩阵的形式查找两组之间的距离。找到小于阈值的元素 (cdist(ind, dep, . . . ) &lt; dist),找到其中包含 True 的任何列 (k = np.any( . . . , axis = 1)),然后再次将所有坐标写入磁盘 (np.savetxt(ind[k] . . .))

如果您有很多值,您可能希望使用 scipy.spatial.KDTree 代替

from scipy.spatial import KDTree
def kd_near_fn(*args, dist = 2., outfile = "practicefilecreate.txt"):
    trees = [KDTree(arg) for arg in args]
    if len(trees) == 1:
        i, j = trees[0].query_pairs(dist)
        k = np.unique(np.r_[i, j])
    elif len(trees) == 2:
        queries = trees[0].query_ball_tree(trees[1], dist)
        k = np.array([len(query) > 0 for query in queries])
    else:
        assert False, "too many inputs"
    np.savetxt(args[0][k], outfile, delimiter = ',')

【讨论】:

  • Daniel F 非常感谢您的回复。我非常感谢您包含的每个步骤的细分和描述。作为计算机编程的新手,这对我来说非常有教育意义
  • 请随意投票并检查答案是否最有帮助:)
  • 我一直在尝试使用 KDTree,但无法让它工作。我不确定我把我的动物点放在哪里。我是否将它们视为 KDTree 参数中的参数?例如。在定义 def_kd_near_fn(*args ..... 我会在这里定义 animalx, animaly 吗?) 然后在 trees= [KDTree(arg-animalx, animaly] 中引用它们,然后 i,j 对与 X,Y 相关我试图根据 AnimalXY 对提取的植被文件对?
  • 您放入一个或两个点数组,具体取决于您是要查找一个数组内的距离还是两个数组之间的距离。 *args 可以是任意数量的参数,在这种情况下,我将其限制为 1 或 2。
猜你喜欢
  • 2015-11-23
  • 1970-01-01
  • 2021-01-16
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多