OO7
OO7

Reputation: 450

Sorting muliple columns of Dataframe on custom

Trying to sort columns based on the priority of "Num" & "Time" but getting unhashable error. Please let me know if there is any other efficient method.

df = pd.DataFrame({'Num': {0: '1-1.1', 1: '1-2.1', 2: '1-10.1', 3: '1-10.2', 4: '1-2.1', 5: '1-2.1', 6: '1-2.2', 7: '1-20.1', 8: '1-20.2', 9: '1-3.1'}, 'Time': {0: '1/8/2021  1:56:48 AM', 1: '1/9/2021  1:56:48 AM', 2: '1/10/2021  1:56:48 AM', 3: '1/11/2021  1:56:48 AM', 4: '1/21/2021  1:56:48 AM', 5: '1/12/2021  1:56:48 AM', 6: '1/13/2021  1:56:48 AM', 7: '1/14/2021  1:56:48 AM', 8: '1/15/2021  1:56:48 AM', 9: '1/16/2021  1:56:48 AM'}})
df['Time'] = pd.to_datetime(df['Time'])

df["range"] = df["Num"].apply(lambda x: [float(y) for y in x.split("-")])

df.sort_values(["range",'Time'], ascending=[True,False])
print (df)

Upvotes: 1

Views: 24

Answers (1)

jezrael
jezrael

Reputation: 862851

Convert list to tuple and assign ouput from sorting to variable:

df["range"] = df["Num"].apply(lambda x: tuple([float(y) for y in x.split("-")]))

df = df.sort_values(["range",'Time'], ascending=[True,False])
print (df)
      Num                Time        range
0   1-1.1 2021-01-08 01:56:48   (1.0, 1.1)
4   1-2.1 2021-01-21 01:56:48   (1.0, 2.1)
5   1-2.1 2021-01-12 01:56:48   (1.0, 2.1)
1   1-2.1 2021-01-09 01:56:48   (1.0, 2.1)
6   1-2.2 2021-01-13 01:56:48   (1.0, 2.2)
9   1-3.1 2021-01-16 01:56:48   (1.0, 3.1)
2  1-10.1 2021-01-10 01:56:48  (1.0, 10.1)
3  1-10.2 2021-01-11 01:56:48  (1.0, 10.2)
7  1-20.1 2021-01-14 01:56:48  (1.0, 20.1)
8  1-20.2 2021-01-15 01:56:48  (1.0, 20.2)

Upvotes: 1

Related Questions