【问题标题】:Get Latitude and Longitude from a column in a dataframe从数据框中的列中获取纬度和经度
【发布时间】:2020-12-03 03:27:49
【问题描述】:

我正在尝试从以下数据框中的“坐标”列中获取纬度和经度,并在同一 df 中创建相应的“纬度”和“经度”列,但没有成功。

import pandas as pd
test_df = pd.DataFrame({'name': ['Wakefield', 'Co-op City'], 
                   'coordinates': ['[[-73.84720055104846, 40.89470566842616]]', '[[-73.82993909620285, 40.87429474550749]]']})

代码:

test_df['Lat'] = test_df.coordinates.str.split('[[',1)[1].split(']]')[0].split(', ')[1]
test_df['Lon'] = test_df.coordinates.str.split('[[',1)[1].split(']]')[0].split(', ')[0]

Output: 
error: unterminated character set at position 0

但是,如果我对单个字符串执行相同的操作。

coord = '[[-73.84720055104846, 40.89470566842616]]'
#longitute
longitude = coord.split('[[',1)[1].split(']]')[0].split(', ')[0]
print('Longitude: ',longitude)

Longitude:  -73.84720055104846

有人知道怎么解决吗? 谢谢

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    在此数据框中,您有一个字符串而不是列表,因此您需要使用 pandas 字符串访问器 .str 并使用 string methods

    使用此代码:

    test_df[['Lat', 'Long']] = test_df['coordinates'].str.strip('\[|\]')\
                                                     .str.split(',', expand=True)
    
    test_df
    

    输出:

             name                                coordinates                 Lat                Long
    0   Wakefield  [[-73.84720055104846, 40.89470566842616]]  -73.84720055104846   40.89470566842616
    1  Co-op City  [[-73.82993909620285, 40.87429474550749]]  -73.82993909620285   40.87429474550749
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-04
      • 2016-12-06
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多