I have a table of the above logic, where I have a road that made up of segments and each segment have a start and stop node. How can I sort the table such that for each road, the segments are sorted in their relative order (which is not in numerical order but dependent on the start and end node)? Also after that I want to add two columns, 'Start' and 'End', to provide the start and end node of the road. The output of the above table should be
import pandas as pd
data = [['Road_id','Segment_id','Start_node','End_node'], [1,8285,4740,4741], [1,8509,4741,5144], [1,8437, 5016,5017], [1,8447, 5031, 5016], [1, 8520, 5144,5168], [1,9104,5168,4785],[1,8550,5017,4740]]
df = pd.DataFrame(data[1:], columns = data[0])
CodePudding user response:
data = [['Road_id','Segment_id','Start_node','End_node'], [1,8285,4740,4741], [1,8509,4741,5144], [1,8437, 5016,5017], [1,8447, 5031, 5016], [1, 8520, 5144,5168], [1,9104,5168,4785]]
df = pd.DataFrame(data[1:], columns = data[0])
df = df.reindex(np.random.permutation(df.index))
df
df.sort_values(['Start_node','End_node'])