Sanya
Sanya

Reputation: 159

Convert DataFrame to multidimensional array following a format

I want to create a multi-dimensional array from the data frame that has over 60,000 rows.

Dataframe:

latitude_1  longitude_1  latitude_2  longitude_2
40.781855   -73.877439   43.689741   -79.581691
40.780243   -73.874084   27.959553   -82.542491
40.781982   -73.878113   33.649540   -84.401093
​

I want to make an array with this format (using Python): [ [[lat1,lon1],[lat2,lon2]], [[lat1,lon1],[lat2,lon2]], [[lat1,lon1],[lat2,lon2]] ]

Is there a way to make this happen? I tried and searched but couldn't find something that can split a row into two arrays or something like that.

Any help would be appreciated!

Upvotes: 2

Views: 1026

Answers (1)

francisb
francisb

Reputation: 61

Can use a normal for loop here this works but if the number of rows are very large it becomes very slow.

new_list = []
for i in range(len(df1)):
    new_list.append([[df1["latitude_1"][i],df1["longitude_1"][i]],[df1["latitude_2"][i],df1["longitude_2"][i]]])

This will faster than using the for loop

new_list = df.values.ravel()
new_list.reshape(len(df),2,2)

Upvotes: 1

Related Questions