簡體   English   中英

僅從列中提取數字並拆分為不同的列

[英]Extract from column only the digits and split to different columns

我有非常大的 dataframe,其中一行通常看起來像這樣:

>>>ID    name    year    location
0  341   Dali    1995   {{"{\"latitude\":\"9.4714611480000004\",\"longitude\":\"4.3520187860000004\"}","{\"latitude\":\"9.4720611479999999\",\"longitude\":\"4.3520187860000004\"}}
...

df['geolocation'] = df['geolocation'].str.replace(r'\D', '') 我想將位置列分成許多只包含數字的列並擺脫“緯度”、“經度”以及它們之間的所有符號。

我想首先通過只提取這樣的數字來做到這一點:

df['location'] = df['location'].str.extract('(\d+)', expand=False)

但出於某種原因,這給了我 integer 號中的位置列。

我不想使用 split 因為中間的符號不一致,有時你有這個序列:{{"{" 有時它只能是 "{"{" 而且我無法真正追蹤所有的可能性可能在那里。不同行中的位數也不同。

我想要的結果應該是這樣的:

>>>ID    name    year    lat                 long                     lat1          long1 ....
0  341   Dali    1995    9.4714611480000004  4.3520187860000004 9.4720611479999999 4.3520187860000004

編輯:我也試過這個:

df['location'] = df['location'].str.replace(r'\D', '')

它保留了數字但給了我一個非常小的數字,沒有保留“。” 並且數字之間也沒有任何空格

我使用正則表達式匹配來有效提取緯度和經度。 這可以使用以下代碼獲得。

import re
import pandas as pd

df = pd.DataFrame({
    'ID': [341,321],
    'name':['Dali','daLi'],
    'year':[1995, 1996],
    'location':['{{"{\"latitude\":\"9.4714611480000004\",\"longitude\":\"4.3520187860000004\"}","{\"latitude\":\"9.4720611479999999\",\"longitude\":\"4.3520187860000004\"}}',
                '{{"{\"latitude\":\"9.4714611480000004\",\"longitude\":\"4.3520187860000004\"}","{\"latitude\":\"9.4720611479999999\",\"longitude\":\"4.3520187860000004\"}}']
})

解決方案

df_new = df.location.apply(lambda x: re.findall(r"\d+\.*\d*",x))
df_new = pd.DataFrame(df_new.to_list(), columns=['lat1','long1','lat2','long2'])
pd.concat([df.iloc[:,0:3], df_new], axis=1)

output

    ID  name    year    lat1                long1               lat2                long2
0   341 Dali    1995    9.4714611480000004  4.3520187860000004  9.4720611479999999  4.3520187860000004
1   321 daLi    1996    9.4714611480000004  4.3520187860000004  9.4720611479999999  4.3520187860000004

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM