从数字字符串列中删除不需要的字符串

2024-04-25 20:01:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从wikipedia收集的数据框,它以lat long coords作为col,我正在尝试删除出现在部分行(而不是全部行)中的参数之间的字符串

样本:

25     53.74333, 91.38583
47    -10.167, 148.700 (Abau Airport)
155    16.63611, -14.19028
414    49.02528, -122.36000
1      16.01111, 43.17778
176    35.34167, 1.46667 (Abdelhafid Boussouf Bou Ch...)

我试过这么做

big_with_ll['Lat_Lon'] = big_with_ll['Lat_Lon'].apply(lambda x: float(x.replace('[^\d.]', '')))

它抛出了这个错误,基本上表明并不是所有的字符都要删除,这很好,但是如果我尝试实现for循环来使用try/catch,那么我将不得不映射,在这个数据帧的情况下,我没有唯一的ID用作键

ValueError: could not convert string to float: '53.58472, 14.90222' 

卸下浮子铸件并执行以下操作:

big_with_ll['Lat_Lon'] = big_with_ll['Lat_Lon'].apply(lambda x: x.replace('[^\d.]', ''))

代码执行了,但是没有做任何更改,我不知道为什么

预期输出应如下所示:

25     53.74333, 91.38583
47    -10.167, 148.700
155    16.63611, -14.19028
414    49.02528, -122.36000
1      16.01111, 43.17778
176    35.34167, 1.46667

Tags: 数据lambdawithcolcoordswikipediafloatreplace
2条回答

不要使用python的str.replace,而是使用pandasDataFrame.replaceregex=True选项。因此,你的路线应该是:

big_with_l['Lat_Lon'] = big_with_ll['Lat_Lon'].replace(r'[^\d.]', '', regex=True)

只是提醒一下,我以为你的正则表达式字符串格式正确

这只是一个简单的正则表达式:

 df.Lat_Lon.str.extract('^([-\d\.,\s]+)')

输出:

                        0
25     53.74333, 91.38583
47       -10.167, 148.700
155   16.63611, -14.19028
414  49.02528, -122.36000
1      16.01111, 43.17778
176     35.34167, 1.46667

您可以提取纬度和经度:

df.Lat_Lon.str.extract('^(?P<Lat>[-\d\.]+),\s(?P<Lon>[-\d\.]+)')

输出:

          Lat         Lon
25   53.74333    91.38583
47    -10.167     148.700
155  16.63611   -14.19028
414  49.02528  -122.36000
1    16.01111    43.17778
176  35.34167     1.46667

相关问题 更多 >