Pandas DataFrame.apply:使用两列数据创建新列

5

I have a DataFrame (df) like this:

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格式(基本上是一个Python字典)呈现的数据。

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

对于单个值,我可以成功地执行:

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

对于单个参数,我成功地使用了dataFrame.apply与lambda结合的方法(感谢StackOverflow:相关问题)。
但现在,我有两个参数,并且想将其应用于整个DataFrame。由于我对.apply语法和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'])))

...但这样行不通,因为该函数将注入整个系列。

编辑: 我发现时间戳地理JSON的格式应该是这样的:

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

所以时间元素在属性元素中,但这并没有改变问题的本质。

你能否更新你的数据框以添加坐标? - Tbaki
@Ulu83 - 嗯,你的输入数据期望得到什么输出? - jezrael
1个回答

5
您需要使用具有axis=1DataFrame.apply函数来按行处理数据框:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接