2016-09-21 86 views
1

这无疑是一个“看不见树木”时刻。我一直盯着这个代码一个小时,看不到我做错了什么。我知道它正在盯着我,但我看不到它!在Pandas数据框中使用pyproj投影之间的转换

我试图在使用Python的两个地理坐标系之间进行转换。

我有经度(x轴)和纬度(y轴)的值和要转换为OSGB 1936对于单个点,我可以执行以下操作:

import numpy as np 
import pandas as pd 
import shapefile 
import pyproj 

inProj = pyproj.Proj(init='epsg:4326') 
outProj = pyproj.Proj(init='epsg:27700') 

x1,y1 = (-2.772048, 53.364265) 

x2,y2 = pyproj.transform(inProj,outProj,x1,y1) 

print(x1,y1) 
print(x2,y2) 

这将产生以下:

-2.772048 53.364265 
348721.01039783185 385543.95241055806 

这似乎是合理的,并建议的-2.772048经度被转换为348721.0103978的坐标。

实际上,我想在熊猫数据框中做到这一点。数据框包含包含经度和纬度的列,我想添加两个包含转换坐标(称为newLong和newLat)的附加列。

的典范据帧可能是:

latitude longitude 
0 53.364265 -2.772048 
1 53.632481 -2.816242 
2 53.644596 -2.970592 

而且我写的代码是:

import numpy as np 
import pandas as pd 
import shapefile 
import pyproj 

inProj = pyproj.Proj(init='epsg:4326') 
outProj = pyproj.Proj(init='epsg:27700') 

df = pd.DataFrame({'longitude':[-2.772048,-2.816242,-2.970592],'latitude':[53.364265,53.632481,53.644596]}) 

def convertCoords(row): 
    x2,y2 = pyproj.transform(inProj,outProj,row['longitude'],row['latitude']) 
    return pd.Series({'newLong':x2,'newLat':y2}) 

df[['newLong','newLat']] = df.apply(convertCoords,axis=1) 

print(df) 

主要生产:

latitude longitude  newLong   newLat 
0 53.364265 -2.772048 385543.952411 348721.010398 
1 53.632481 -2.816242 415416.003113 346121.990302 
2 53.644596 -2.970592 416892.024217 335933.971216 

但现在看来,NEWLONG和newLat值混淆了(与上面显示的单点转换的结果相比)。

我在哪里划过电线来产生这个结果? (我很抱歉,如果它是完全明显的!)

回答

3

当你做df[['newLong','newLat']] = df.apply(convertCoords,axis=1),你正在索引df.apply输出的列。但是,列顺序是任意的,因为你的系列是用字典定义的(这本质上是无序的)。

您可以选择与固定的列排序返回系列:

return pd.Series([x2, y2]) 

另外,如果你想保持convertCoords输出标记,那么你可以使用.join到结果,而不是合并:

return pd.Series({'newLong':x2,'newLat':y2}) 
... 
df = df.join(df.apply(convertCoords, axis=1)) 
+0

非常感谢您提供的答案和即时解决方案。 – user1718097