2017-06-16 112 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