Reputation: 617
Long story short : I've got a DataFrame like this template :
city Longitude Latitude
0 Gotham City 35.699708 2.158089
1 Xibalba 35.676700 4.199400
2 Eldorado 35.680871 6.165926
3 Atlantis 35.680339 8.165897
4 Elysium 35.678219 10.165940
5 Lost City of Z 35.678037 12.166077
6 Parnasius 35.678192 14.165853
And I used an algorithm to solve the Traveling Salesman Problem. My solution is a list, like this :
sorting_order = [4,5,2,1,0,6,3]
To be clear, df.iloc[4] should be in first position, then df.iloc[5], df.iloc[2], etc... So I created a new empty DF :
df_sorted = pd.DataFrame(columns =['city','Longitude','Latitude'])
And finally, I tried this simple for loop to update df_sorted in the right oder :
for index in sorting_order:
df_sorted.append(df.iloc[index])
But df_sorted remains empty at the end of the loop... Could I update a new DF using the iloc of an other or not ?
Upvotes: 0
Views: 994
Reputation: 150745
You already mention iloc
, why don't you try:
df.iloc[sorting_order]
Output:
city Longitude Latitude
4 Elysium 35.678219 10.165940
5 Lost City of Z 35.678037 12.166077
2 Eldorado 35.680871 6.165926
1 Xibalba 35.676700 4.199400
0 Gotham City 35.699708 2.158089
6 Parnasius 35.678192 14.165853
3 Atlantis 35.680339 8.165897
Upvotes: 2
Reputation: 109546
Just re-index the dataframe, then reset the index.
>>> df.reindex(sorting_order).reset_index(drop=True)
city Longitude Latitude
0 Elysium 35.678219 10.165940
1 Lost_City_of_Z 35.678037 12.166077
2 Eldorado 35.680871 6.165926
3 Xibalba 35.676700 4.199400
4 Gotham_City 35.699708 2.158089
5 Parnasius 35.678192 14.165853
6 Atlantis 35.680339 8.165897
Upvotes: 1