pandas - 将 UTM 函数应用于数据框列

Fab*_*nna 2 python utm pandas

我正在使用这个名为 UTM 的 python 包,它将 WGS84 坐标转换为 UTM,反之亦然。我想将此函数应用于 pandas 数据框。该函数的工作原理如下:

utm.from_latlon(51.2, 7.5)
>>> (395201.3103811303, 5673135.241182375, 32, 'U')
Run Code Online (Sandbox Code Playgroud)

其中输入是几个坐标,它返回 UTM 系统中相同坐标的元组。出于我的目的,我只对元组的前两个元素感兴趣。

我正在开发一个名为的数据框cities

City;Latitude;Longitude;minx;maxx;miny;maxy
Roma;41.892916;12.48252;11.27447419;13.69056581;40.99359439;42.79223761
Paris;48.856614;2.352222;0.985506011;3.718937989;47.95729239;49.75593561
Barcelona;41.385064;2.173403;0.974836927;3.371969073;40.48574239;42.28438561
Berlin;52.519171;13.406091;11.92835553;14.88382647;51.61984939;53.41849261
Moscow;55.755826;37.6173;36.01941671;39.21518329;54.85650439;56.65514761
Run Code Online (Sandbox Code Playgroud)

我想为每行添加四列,称为 'utmminx'、'utmmax'、'utmminy'、'utmmaxy' 作为将 utm 函数应用于 'minx'、'maxx'、'miny'、' 的结果maxy' 列。到目前为止,我尝试了以下操作,将结果元组的第一个和第二个值分配给新列:

cities['utmminx'],cities['utmmaxx'] = utm.from_latlon(cities['minx'],cities['maxx'])[0],utm.from_latlon(cities['minx'],cities['maxx'])[1]
Run Code Online (Sandbox Code Playgroud)

但我收到了一条消息,ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().我尝试仅将第一行值设置为函数,并且它有效:

utm.from_latlon(cities['minx'][0],cities['maxx'][0])[0],utm.from_latlon(cities['minx'][0],cities['maxx'][0])[1]
>>> (357074.7837193568, 1246647.7959235134)
Run Code Online (Sandbox Code Playgroud)

我想避免数据帧上的经典循环,因为我认为有一个经典的 pandas 方法可以做到这一点。

Zer*_*ero 5

apply您可以在列上使用方法,例如

使用 lambda 函数

In [120]: lambdafunc = lambda x: pd.Series(utm.from_latlon(x['minx'], x['maxx'])[:2])
Run Code Online (Sandbox Code Playgroud)

并且,逐行应用

In [121]: cities[['utmminx', 'utmmax']] = cities.apply(lambdfunc), axis=1)

In [122]: cities
Out[122]:
        City   Latitude  Longitude       minx       maxx       miny       maxy        utmminx          utmmax
0       Roma  41.892916  12.482520  11.274474  13.690566  40.993594  42.792238  357074.783719  1246647.795924
1      Paris  48.856614   2.352222   0.985506   3.718938  47.957292  49.755936  579990.155575   108936.764630
2  Barcelona  41.385064   2.173403   0.974837   3.371969  40.485742  42.284386  541385.186664   107751.160445
3     Berlin  52.519171  13.406091  11.928356  14.883826  51.619849  53.418493  487350.117333  1318634.001517
4     Moscow  55.755826  37.617300  36.019417  39.215183  54.856504  56.655148  519389.217259  3986123.464910
Run Code Online (Sandbox Code Playgroud)