2017-06-16 84 views
1

我有一个数据帧(DF)这样创建数据的新列:熊猫DataFrame.apply:从两列

PointID Time     geojson 
----  ----     ----  
36F  2016-04-01T03:52:30 {'type': 'Point', 'coordinates': [3.961389, 43.123]} 
36G  2016-04-01T03:52:50 {'type': 'Point', 'coordinates': [3.543234, 43.789]} 

的GeoJSON的列包含以GeoJSON格式(esentially,Python字典)数据。

我想创建GeoJSON格式导出一个新列,其中包括时间坐标。换句话说,我要注入的时间信息到GeoJSON的信息。

对于单个值,我可以成功做到:

oldjson = df.iloc[0]['geojson'] 
newjson = [df['coordinates'][0], df['coordinates'][1], df.iloc[0]['time'] ] 

对于单个参数,我成功地使用dataFrame.apply结合拉姆达(感谢SO:related question

但现在,我有两个参数,我想用它在整个数据帧由于我没有信心用。适用语法和lambda,我不知道这甚至有可能,我想这样做:。

def inject_time(geojson, time): 
""" 
Injects Time dimension into geoJSON coordinates. Expects a dict in geojson POINT format. 
""" 
geojson['coordinates'] = [geojson['coordinates'][0], geojson['coordinates'][1], time] 
return geojson 


df["newcolumn"] = df["geojson"].apply(lambda x: inject_time(x, df['time']))) 

...但是,这是不行的,因为该函数将注入全系列。

编辑: 我想通了时间戳以GeoJSON格式应该是这样的:

TimestampedGeoJson({ 
      "type": "FeatureCollection", 
       "features": [ 
       { 
        "type": "Feature", 
        "geometry": { 
        "type": "LineString", 
        "coordinates": [[-70,-25],[-70,35],[70,35]], 
        }, 
        "properties": { 
        "times": [1435708800000, 1435795200000, 1435881600000] 
        } 
        } 
       ] 
       }) 

所以时间因素是在properties元素,但是这并没有太大变化的问题。

+0

您可以更新您的数据框添加坐标? – Tbaki

+0

@ Ulu83 - 嗯,期望从你的输入数据的输出? – jezrael

回答

2

您可以通过行需要DataFrame.applyaxis=1进行处理:

df['new'] = df.apply(lambda x: inject_time(x['geojson'], x['Time']), axis=1) 

#temporary display long string in column 
with pd.option_context('display.max_colwidth', 100): 
    print (df['new']) 

0 {'type': 'Point', 'coordinates': [3.961389, 43.123, '2016-04-01T03:52:30']} 
1 {'type': 'Point', 'coordinates': [3.543234, 43.789, '2016-04-01T03:52:50']} 
Name: new, dtype: object