我的 pandas DataFrame 的專欄中有一個非常不規則的運算式。我想洗掉除坐標之外的所有內容。但是,我不能只使用替換或洗掉功能,因為我要洗掉的部分在每列中都不同。有沒有辦法只選擇我真正想要使用的部分字串?
一個單元格如下所示:
{'is_geometry': True, 'configuration': 'technologies', 'additional_translations': {}, 'key': 'Map', 'value': '{"type":"FeatureCollection","features":[{"type":"Feature","id":1549869006355,"geometry":{"type":"Point","coordinates":[67.91225703380735,34.69585762863356]},"properties":null}]}', 'map_url': '/en/technologies/view/technologies_1723/map/', 'template': 'raw'}
其中 id 和 map_url 總是不同的。在這個例子中,我只想有 [67.91225703380735,34.69585762863356]。此外,有沒有辦法改變這兩個值,以便我有 [34.69585762863356,67.91225703380735] 代替?
uj5u.com熱心網友回復:
我不確定你到底想要什么,但假設你的資料框的列包含像你的例子一樣的字典,這應該可以作業:
import ast
import json
df['nums'] = df.loc[df['tech_map'].notna(), 'tech_map'].astype(str).apply(ast.literal_eval).str['value'].apply(json.loads).str['features'].str[0].str['geometry'].str['coordinates'].str[::-1]
兩個注意事項: - 上面基本上相當于json.loads(row['value'])['features'][0]['geometry']['coordinates'][::-1]為每一行做 -[::-1]反轉一個串列
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/443061.html
