带有空值的dataframe列中的额外dict值

时间:2017-06-30 18:44:36

标签: python-2.7 pandas

我有一个由JSON数据构成的数据框。我遇到的问题是两列包含字典。我设法使用迭代器从其中一列中提取值,但另一列也包含一些导致错误的空单元格。

这是我的数据帧的一部分(

    area                                           latLng     price
0   191.0  {u'latitude': 52.000000, u'longitude': 5.220000}   120000
1   192.0  {u'latitude': 52.080000, u'longitude': 5.240000}   420000
2   140.0  {u'latitude': 52.100000, u'longitude': 5.230000}   175000
3   180.0                                             None    165000
...

(我出于隐私原因编辑了lat / lng值)

问题在于latLng列。我想在不同的列中获取纬度和经度,以便我可以轻松使用该位置。

我为另一个类似的列尝试了以下代码,并且运行正常。但latLng列包含一些导致问题的空单元格:

df["lat"] = [d.get('latitude') for d in df.latLng]
df["lon"] = [d.get('longitude') for d in df.latLng]

AttributeError: 'NoneType' object has no attribute 'get'

我也尝试过使用某种if语句,但我似乎并没有这样做。

df["lat"] = [d.get('latitude') for d in df.latLng if d.notnull()]

AttributeError: 'dict' object has no attribute 'notnull'

有人可以就如何解决这个问题提供一些帮助吗?

1 个答案:

答案 0 :(得分:1)

您可以在列表推导中添加条件,如下所示。 latlngNone的地方,latlon最终为NaN

df['lat'] = [d.get('latitude') if d is not None else None for d in df.latlng]
df['lon'] = [d.get('longitude') if d is not None else None for d in df.latlng]