ServicePop 有 x、y 坐標,我想添加一個平方數(gid)。我做了一個嵌套的 for 回圈來分配一個平方數,但 ServicePop 太大了,需要幾個小時。有沒有更快更有效的方法來做到這一點?當我在谷歌搜索時,他們說使用資料框或矢量化的應用會有所幫助,但我無法更改我的代碼以使用這樣的改進。
我需要你的幫助,請。
import pandas
import datetime
TotPopCenter = pandas.read_csv('TotalPopulationCurrentCenterShapeCoordinate_UTF8.csv', encoding='euckr')
ServicePop = pandas.read_csv('202101_Final.csv', encoding='euckr')
ServicePop.insert(9,'gid','')
Service_gid = ['' for _ in range(len(ServicePop))]
for j in range(len(ServicePop)):
for i in range(len(TotPopCenter)):
if (ServicePop['X_COORD'][j] >= TotPopCenter['xcoord'][i]-125) and \
(ServicePop['X_COORD'][j] < TotPopCenter['xcoord'][i] 125) and \
(ServicePop['Y_COORD'][j] >= TotPopCenter['ycoord'][i]-125) and \
(ServicePop['Y_COORD'][j] < TotPopCenter['ycoord'][i] 125):
Service_gid[j] = TotPopCenter['gid'][I]
ServicePop['gid'] = Service_gid
TotPopCenter GID LBL VAL XCOORD YCOORD 0 LM87ab60ba楠楠1087375 1760625 ServicePop STD_YMD X_COORD Y_COORD HCODE WKDY_CD TIME HPOP WPOP VPOP 0 2021年1月1日1.087484e 06 1.760579e 06 2207061 FRI 0 27.97 0.82 7.24
uj5u.com熱心網友回復:
如果您想專門優化嵌套回圈,您可能需要使用itertools.product,使用:
import itertools
for j, i in itertools.product(range(len(ServicePop)), range(len(TotPopCenter))):
而不是:
for j in range(len(ServicePop)):
for i in range(len(TotPopCenter)):
uj5u.com熱心網友回復:
我會存盤值而不是不斷查找
for j in range(len(ServicePop)):
serviceX = ServicePop['X_COORD'][j]
serviceY = ServicePop['Y_COORD'][j]
for i in range(len(TotPopCenter)):
totX = TotPopCenter['xcoord'][i]
totY = TotPopCenter['ycoord'][i]
if (serviceX >= totX - 125) and \
(serviceX < totX 125) and \
(serviceY >= totY - 125) and \
(serviceY < totY 125):
如果您知道它們不會重疊,也許您甚至可以盡早中斷內部回圈。也許之前對 TotPopCenter 進行排序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/399313.html
上一篇:迭代串列以創建df
