我得到了一个CSV文件,其中包含下一种格式的GIS模型中质心之间的距离:
InputID,TargetID,Distance
1,2,3050.01327866
1,7,3334.99565217
1,5,3390.99115304
1,3,3613.77046864
1,4,4182.29900892
...
...
3330,3322,955927.582933
它按起点(InputID
)排序,然后按最近的目的地(TargetID
)排序。你知道吗
对于特定的建模工具,我需要CSV文件中的数据,格式如下(数字是质心数字):
distance1->1, distance1->2, distance1->3,.....distance1->3330
distance2->1, distance2->2,.....
.....
distance3330->1,distance3330->2....distance3330->3330
所以没有InputID或TargetID,只有行上的起点和列上的目的地的距离: (前5个出发地/目的地示例)
0,3050.01327866,3613.77046864,4182.29900892,3390.99115304
3050.01327866,0,1326.94611797,1175.10254872,1814.45584129
3613.77046864,1326.94611797,0,1832.209595,3132.78725738
4182.29900892,1175.10254872,1832.209595,0,1935.55056767
3390.99115304,1814.45584129,3132.78725738,1935.55056767,0
我已经建立了下一个代码,它的工作。但是它太慢了,运行它需要几天才能得到3330x3330文件。由于我是Python的初学者,我想我忽略了一些东西。。。你知道吗
import pandas as pd
import numpy as np
file=pd.read_csv('c:\\users\\Niels\\Dropbox\\Python\\centroid_distances.csv')
df=file.sort_index(by=['InputID', 'TargetID'], ascending=[True, True])
number_of_zones=3330
text_file = open("c:\\users\\Niels\\Dropbox\\Python\\Output.csv", "w")
for origin in range(1,number_of_zones):
output_string=''
print(origin)
for destination in range(1,number_of_zones):
if origin==destination:
distance=0
else:
distance_row=df[(df['InputID']==origin) & (df['TargetID'] == destination)]
# I guess this is the time-consuming part
distance=distance_row.iloc[0]['Distance']
output_string=output_string+str(distance)+','
text_file.write(output_string[:-1]+'\n') #strip last ',' of line
text_file.close()
你能给我一些提示来加速这个代码吗?你知道吗
IIUC,你只需要
pivot
。如果你从这样的画面开始:我们知道InputID和TargetID是唯一的,我们可以简单地
pivot
:教程的reshaping部分可能很有用。你知道吗
相关问题 更多 >
编程相关推荐