问题描述
dfjson = pd.read_json(path_or_buf=JsonFicMain,orient='records',lines=True)
nomCommune codeCommune numeroComplet nomVoie codePostal meilleurePosition codesParcelles
0 Ablon-sur-Seine 94001 21 Rue Robert Schumann 94480 {'type': 'parcelle','geometry': {'type': 'Point','coordinates': [2.411247955172414,48.726054248275865]}} [94001000AG0013]
1 Ablon-sur-Seine 94001 13 Rue Robert Schumann 94480 {'type': 'parcelle','coordinates': [2.412065866666666,48.72614911111111]}} [94001000AG0020]
它包含一百万行,我想在一个特定的列(名为meilleurePosition)中提取方括号之间的一个地理坐标。预期的输出是
[2.411247955172414,48.726054248275865]
我试图提取坐标或替换所有其他不需要的字符 使用extractall,否则extract不匹配
test=dfjson['meilleurePosition'].str.extract(pat='(\d+\.\d+)')
test2=dfjson['meilleurePosition'].str.extractall(pat='(\d+\.\d+)')
Empty DataFrame
Columns: [0]
Index: []
使用替换或str.replace不起作用
test3=dfjson["meilleurePosition"].replace(to_replace=r'[^0-9.,:]',value='',regex=True)
0 {'type': 'parcelle',48.726054248275865]}}
1 {'type': 'parcelle',48.72614911111111]}}
即使正则表达式类型也不起作用
test4=dfjson['meilleurePosition'].str.replace('type','whatever')
0 NaN
1 NaN
print(test)
我试图找出为什么这根本不起作用。
- 列类型为“对象”(这很好,因为这是一个 字符串)
- 使用inplace = True而不复制数据框会导致 类似结果
为什么我不能操作此列,是因为其中包含特殊字符? 如何以良好的格式获取这些坐标?
好吧,经过更多调查,该列包含一个嵌套的dict,这就是为什么它不起作用的原因 这个答案对我很有帮助 python pandas use map with regular expressions 然后,我确实使用以下代码创建了具有预期坐标的新列
def extract_coord(meilleurepositiondict):
if isinstance(meilleurepositiondict,dict) :
return meilleurepositiondict['geometry']['coordinates']
else :
return None
dfjson['meilleurePositionclean']=dfjson['meilleurePosition'].apply(lambda x: extract_coord(x))
解决方法
我使用下面的代码找到了解决方案
dfjson['meilleurePosition']=dfjson['meilleurePosition'].apply(lambda x: extract_coord(x) if x == x else defaultmeilleurepositionvalue)
这是必需的,因为空行会导致错误(未困在函数定义中)。 但是,我仍然相信,有很多简单的方法可以将列的dict值分配给该列本身,仍在尝试...