在python中通过数组循环查找欧几里德距离

2024-09-23 06:36:37 发布

您现在位置:Python中文网/ 问答频道 /正文

到目前为止,我得到的是:

Stats2003 = np.loadtxt('/DataFiles/2003.txt') 
Stats2004 = np.loadtxt('/DataFiles/2004.txt') 
Stats2005 = np.loadtxt('/DataFiles/2005.txt') 
Stats2006 = np.loadtxt('/DataFiles/2006.txt')
Stats2007 = np.loadtxt('/DataFiles/2007.txt') 
Stats2008 = np.loadtxt('/DataFiles/2008.txt')
Stats2009 = np.loadtxt('/DataFiles/2009.txt') 
Stats2010 = np.loadtxt('/DataFiles/2010.txt') 
Stats2011 = np.loadtxt('/DataFiles/2011.txt') 
Stats2012 = np.loadtxt('/DataFiles/2012.txt') 

Stats = Stats2003, Stats2004, Stats2004, Stats2005, Stats2006, Stats2007, Stats2008, Stats2009, Stats2010, Stats2011, Stats2012

我试图计算这些数组和其他数组之间的欧几里德距离,但我做起来有困难。在

通过计算距离,我可以得到如下输出:

^{pr2}$

但是我想用一个循环来做这些计算。在

我用Prettytable将计算结果显示到一个表格中。在

谁能给我指出正确的方向吗?我之前没有找到任何有效的解决方案。在


Tags: txtnp数组datafilesloadtxtstats2012stats2003stats2008
2条回答

要执行循环,您需要keep data out of your variable names。一个简单的解决办法是改用字典。这些循环在dict理解中是隐含的:

import itertools as it

years = range(2003, 2013)
stats = {y: np.loadtxt('/DataFiles/{}.txt'.format(y) for y in years}
dists = {(y1,y2): np.linalg.norm(stats[y1] - stats[y2]) for (y1, y2) in it.combinations(years, 2)}

现在,通过stats[2007]访问特定年份的统计数据,并使用元组(例如dists[(2007, 20011)])访问距离。在

^{}。在

根据文件:

Computes distance between each pair of the two collections of inputs.

所以你可以做如下操作:

import numpy as np
from scipy.spatial.distance import cdist
# start year to stop year
years = range(2003,2013)
# this will yield an n_years X n_features array
features = np.array([np.loadtxt('/Datafiles/%s.txt' % year) for year in years])
# compute the euclidean distance from each year to every other year
distance_matrix = cdist(features,features,metric = 'euclidean')

如果您知道起始年份,并且您没有丢失任何年份的数据,那么很容易确定在距离矩阵的坐标(m,n)处比较哪两年。在

相关问题 更多 >