Reputation: 69
I have the dataframre below .
d = {'id': ['x1', 'x2','x3','x4','x5','x6','x7'],'t1': [3,11,4,4,10,16,8],'t2':[20,14,4,15,22,11,4],
't3':[14,2,12,18,16,16,11]}
df = pd.DataFrame(data=d)
I want to do add column that contains the sort on t1 then if for two lines we have t1 equal then we can have a look on t2 and do the same thing. My column will contain.
df['calculated'] =[7,2,6,5,3,1,4]
My dataframe expected will be:
d = {'id': ['x1', 'x2','x3','x4','x5','x6','x7'],'t1': [3,11,4,4,10,16,8],'t2':[20,14,4,15,22,11,4],
't3':[14,2,12,18,16,16,11],'calculated':[7,2,6,5,3,1,4]}
df = pd.DataFrame(data=d)
Upvotes: 0
Views: 39
Reputation: 862851
Use DataFrame.sort_values
by all columns for test if equal and create new column e.g. by DataFrame.assign
:
df1 = df.sort_values(['t1','t2','t3'], ascending=False).assign(new=range(1, len(df) + 1))
print (df1)
id t1 t2 t3 calculated new
5 x6 16 11 16 1 1
1 x2 11 14 2 2 2
4 x5 10 22 16 3 3
6 x7 8 4 11 4 4
3 x4 4 15 18 5 5
2 x3 4 4 12 6 6
0 x1 3 20 14 7 7
Last if necessary original index add DataFrame.sort_index
:
df1 = df1.sort_index()
print (df1)
id t1 t2 t3 calculated new
0 x1 3 20 14 7 7
1 x2 11 14 2 2 2
2 x3 4 4 12 6 6
3 x4 4 15 18 5 5
4 x5 10 22 16 3 3
5 x6 16 11 16 1 1
6 x7 8 4 11 4 4
Upvotes: 1