将函数应用于不接受NaN的列

2024-04-27 02:27:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要匹配街道名称和数据框中的gps坐标。为此,我使用OSRM;我可以给OSRM一个GPS坐标列表,它会给我名称,但我的系列包含NaN,OSRM不接受Null或Zero,所以我需要过滤掉它们(简单),然后将结果放回相应的行中;我该怎么做?编辑:dataframe中还有一些我不能丢失的列(这里用t表示,但是还有更多)。你知道吗

import pandas as pd
import numpy as np
import requests
import json

path = [
  51.954974, 5.857131,
  51.955014, 5.860725,
  np.nan, np.nan,
  51.954168, 5.866390,
  51.954889, 5.868611,
]
path = [ {'t': t, 'lat': c[0], 'lon': c[1]} for t, c in enumerate(zip(*[path[i::2] for i in range(2)]))]
df = pd.DataFrame(path)

path = ';'.join(list(df[pd.notnull(df.lat)].apply(lambda x: str(x.lon) + ',' + str(x.lat), axis=1)))
osrm = 'http://router.project-osrm.org' # currently down
#osrm = 'http://localhost:5000'
url = osrm + '/match/v1/car/' + path + '?overview=full&annotations=nodes&tidy=true'

# OSRM is down now but this return [ "Metamorfosenallee", "Burgemeester Matsersingel", "Burgemeester Matsersingel", "Batavierenweg" ]
matched = [tp['name'] for tp in requests.post(url).json()['tracepoints']]

# how do I now get
#  t lat        lon        name
#  0 51.954974, 5.857131,  Metamorfosenallee
#  1 51.955014, 5.860725,  Burgemeester Matsersingel
#  2 np.nan,    np.nan,    np.nan
#  3 51.954168, 5.866390,  Burgemeester Matsersingel
#  4 51.954889, 5.868611,  Batavierenweg

(编辑以添加我不想丢失的额外列)


Tags: pathinimport名称dffornpnan
2条回答

可能有许多较短的方法可以达到目标。但你可以尝试下面的步骤。你知道吗

首先,分离包含NaN值的行并将其存储在t。我假设NaN也只能发生在latlon中。你可以改进它。你知道吗

t = df.loc[df.lat.isnull() | df.lon.isnull()]
t
    lat        lon        
2  NaN        NaN 

df中删除具有NaN值的行

df.dropna(inplace=True)
df
    lat        lon        
0  51.954974  5.857131
1  51.955014  5.860725
3  51.954168  5.866390
4  51.954889  5.868611

-

在这里做好你的工作。

-

最后将数据帧t安排回原始数据帧df。你知道吗

df = df.append(t).sort_index()
df
    lat        lon        name
0  51.954974  5.857131   Metamorfosenallee
1  51.955014  5.860725   Burgemeester Matsersingel
2  NaN        NaN        NaN
3  51.954168  5.866390   Burgemeester Matsersingel
4  51.954889  5.868611   Batavierenweg

应用

df.lat.replace(np.nan, '', inplace=True)
df.lon.replace(np.nan, '', inplace=True)

取消功能

相关问题 更多 >