Ducttape19
Ducttape19

Reputation: 475

Extracting dictionary values from dataframe and creating a new Pandas column

I have a Pandas DataFrame with several columns, one of which is a dictionary containing coordinates in a list. This is what the entry looks like:

{'type': 'Point', 'coordinates': [-120.12345, 50.23456]}

I would like to extract this data and create 2 new columns in the original DataFrame, one for the latitude and one for longitude.

ID Latitude Longitude
1 -120.12345 50.23456

I have not been able to find a simple solution at this point and would be grateful for any guidance.

Upvotes: 1

Views: 179

Answers (2)

chsws
chsws

Reputation: 443

You can access dictionary get method through the .str

test = pd.DataFrame(
    {
        "ID": [1, 2],
        "point": [
            {'type': 'Point', 'coordinates': [-120.12345, 50.23456]},
            {'type': 'Point', 'coordinates': [-10.12345, 50.23456]}]
    }, 
)

pd.concat([
    test["ID"],
    pd.DataFrame(
        test['point'].str.get('coordinates').to_list(),
        columns=['Latitude', 'Longitude']
)
],axis=1)

Upvotes: 2

Nk03
Nk03

Reputation: 14949

You can use str to fetch the required structure:

df = pd.DataFrame({'Col' : [{'type': 'Point', 'coordinates': [-120.12345, 50.23456]}]})
df['Latitude'] = df.Col.str['coordinates'].str[0]
df['Longitude'] = df.Col.str['coordinates'].str[1]

OUTPUT:

                                                 Col   Latitude  Longitude
0  {'type': 'Point', 'coordinates': [-120.12345, ... -120.12345   50.23456

Upvotes: 1

Related Questions