0

I have a sample DataFrame as below: First column consists of 2 years, for each year, 2 track exist and each track includes pairs of longitude and latitude coordinated. How can I extract every track for each year separately to obtain an array of tracks with lat and long?

df = pd.DataFrame(
    {'year':[0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1], 
    'track_number':[0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1], 
    'lat': [11.7,11.8,11.9,11.9,12.0,12.1,12.2,12.2,12.3,12.3,12.4,12.5,12.6,12.6,12.7,12.8], 
    'long':[-83.68,-83.69,-83.70,-83.71,-83.71,-83.73,-83.74,-83.75,-83.76,-83.77,-83.78,-83.79,-83.80,-83.81,-83.82,-83.83]})
2
  • What is your desired output? Commented Apr 21, 2021 at 19:44
  • Can you please share what you have tried thus far? Commented Apr 21, 2021 at 20:11

1 Answer 1

1

You can groupby year and then extract a numpy.array from the created dataframes with .to_numpy().

>>> years = []
>>> for _, df2 in df.groupby(["year"]):
        years.append(df2.to_numpy()[:, 1:]) 
>>> years[0]
    array([[  0.  ,  11.7 , -83.68],
           [  0.  ,  11.8 , -83.69],
           [  0.  ,  11.9 , -83.7 ],
           [  0.  ,  11.9 , -83.71],
           [  1.  ,  12.  , -83.71],
           [  1.  ,  12.1 , -83.73],
           [  1.  ,  12.2 , -83.74],
           [  1.  ,  12.2 , -83.75]])
>>> years[1] 
    array([[  0.  ,  12.3 , -83.76],
           [  0.  ,  12.3 , -83.77],
           [  0.  ,  12.4 , -83.78],
           [  0.  ,  12.5 , -83.79],
           [  1.  ,  12.6 , -83.8 ],
           [  1.  ,  12.6 , -83.81],
           [  1.  ,  12.7 , -83.82],
           [  1.  ,  12.8 , -83.83]])

Where years[0] would have the desired information for the year 0. And so on. Inside the array, the positions of the original dataframe are preserved. That is, the first element is the track; the second, the latitude, and the third, the longitude.

If you wish to do the same for the track, i.e, have an array of only latitude and longitude, you can groupby(["year", "track_number"]) as well.

Sign up to request clarification or add additional context in comments.

Comments

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.