2

这无疑是一个“只见树木不见森林”的时刻。我盯着这段代码看了一个小时,看不出我做错了什么。我知道它正盯着我的脸,但我就是看不到它!

我正在尝试使用 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 的坐标。

事实上,我想在 Pandas 数据框中执行此操作。数据框包含包含经度和纬度的列,我想添加两个包含转换坐标的附加列(称为 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 的值混在一起了(对比上面显示的单点转换的结果)。

我在哪里让我的电线交叉以产生这个结果?(如果这完全明显,我道歉!)

4

2 回答 2

4

当你这样做时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))
于 2016-09-21T15:27:07.753 回答
2

请注意,accepts的transform功能也很重要,这在处理大型数据帧时非常有用,并且比使用/功能快得多pyprojarrayslambdaapply

import pandas as pd
from pyproj import Proj, transform

inProj, outProj = Proj(init='epsg:4326'), Proj(init='epsg:27700')
df['newLon'], df['newLat'] = transform(inProj, outProj, df['longitude'].tolist(), df['longitude'].tolist())
于 2019-07-01T07:43:47.290 回答