numpy Python中3D点阵列的欧氏距离

pxy2qtax  于 2022-11-23  发布在  Python
关注(0)|答案(1)|浏览(150)

我有两个3D点的.csv文件(数值坐标数据)和关联的属性数据(字符串+数值)。我需要计算每个点与其他每个点之间的欧氏距离,并维护与差值关联的每个点的属性数据。我有一个方法可以实现此目的,但是它使用了一个循环,我希望有一个更好的方法来实现这个目标,并且资源消耗更少。

import pandas as pd
import numpy as np

# read .csv
dataset_1 = pd.read_csv(dataset1 path)
dataset_2 = pd.read_csv(dataset2 path)

# convert to numpy array
array_1 = dataset_1.to_numpy()
array_2 = dataset_2.to_numpy()

# define data types for new array. This includes the attribute data I want to maintain
data_type = np.dtype('f4, f4, f4, U10, U10, f4, f4, f4, U10, U10, U10, f4, f4, U10, U100')

#define the new array
new_array = np.empty((len(array_1)*len(array_2)), dtype=data_type)

#calculate the Euclidean distance between each set of 3D coordinates, and populate the new array with the results as well as data from the input arrays
number3 = 0
for number in range(len(array_1)):
        for number2 in range(len(array_2)):
                Euclidean_Dist = np.linalg.norm(array_1[number, 0:3]-array_2[number2, 0:3])
                new_array[number3] = (array_1[number, 0], array_1[number, 1], array_1[number, 2], array_1[number, 3], array_1[number, 7],
                 array_2[number2, 0], array_2[number2, 1],array_2[number2, 2], array_2[number2, 3], array_2[number2, 6], array_2[number2, 7],
                 array_2[number2, 12], array_2[number2, 13], dist,''.join(sorted((str(array_2[number2, 0]) + str(array_2[number2, 1]) + str(array_2[number2, 2]) + str(array_2[number2, 3])))))
                number3+=1   
                
#Convert results to pandas dataframe
new_df = pd.DataFrame(new_array)

我处理非常大的数据集,所以如果有人能建议一个更有效的方法来做这件事,我将非常感激。
谢谢你,
上面给出的代码可以解决我的问题,但是我在寻找一些可以提高效率的东西
编辑以显示示例输入数据集(dataset_1 & dataset_2)和所需的输出数据集(new_df)。关键在于,对于输出数据集,我需要维护与欧氏距离关联的输入数据集的属性。我可以使用scipy.spatial.distance.cdist来计算距离,但我不确定在输出数据中维护输入数据的属性的最佳方式。

pgky5nke

pgky5nke1#

两种方法。设置:

import numpy as np
import pandas as pd
import string
from scipy.spatial.distance import cdist

upper = list(string.ascii_uppercase)
lower = list(string.ascii_lowercase)

df1 = pd.DataFrame(np.random.rand(26,3), 
                   columns = lower[-3:], 
                   index = lower )

df2 = pd.DataFrame(np.random.rand(25,3), 
                   columns = lower[-3:], 
                   index = upper[:-1] )  #testing different lengths

使用.merge(*, how='cross'),我认为这会给出您想要的输出

new_df = df1.reset_index().merge(df2.reset_index(), 
                              how = 'cross',
                              suffixes = ['1', '2'])
new_df['dist'] = cdist(df1, df2).flatten()

2D“散乱”方法,将原始数据保持为MultiIndex es:

new_df2 = pd.DataFrame(cdist(df1, df2), 
                   index = pd.MultiIndex.from_arrays(df1.reset_index().values.T, 
                                                     names = df1.reset_index().columns), 
                   columns = pd.MultiIndex.from_arrays(df2.reset_index().values.T, 
                                                     names = df2.reset_index().columns))

相关问题