2

I have a dataframe like this:

long  lat      Place 
-6.779       61.9     Aarhus  
-6.790     62.0       Aarhus      
54.377     24.4       Dhabi   
38.834     9.0        Addis 
35.698     9.2        Addis 
    Is it possible to transform the dataframe into a format like below?

Office    long + lat
Aarhus     [[-6.779,61.9], [-6.790,62.0]]
Dhabi      [[54.377]]
Addis      [[38.834,9.0], [35.698,9.2]]

I tried different methods but still couldn't work this out. This is what I tried to get a list for each distinct place value:

df2["index"] = df2.index
df2["long"]=df2.groupby('index')['long'].apply(list)
list 1= [] 
for values in ofce_list:
    if df['Office'].any() == values:
        list1.append(df.loc[df['Office'] == values, 'long'])

    But this returned a series in a list instead which is not desired. Please help. Thank you so much.

1 Answer 1

3
 df.groupby('Place')[['long','lat']].apply(lambda x :x.values.tolist()).\
      reset_index(name='long + lat')
Out[1380]: 
    Place                       long + lat
0  Aarhus  [[-6.779, 61.9], [-6.79, 62.0]]
1   Addis   [[38.834, 9.0], [35.698, 9.2]]
2   Dhabi     [[54.376999999999995, 24.4]]
Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget the .reset_index(name='long + lat')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.