I have Dataframe:
JavaScript
x
6
1
teamId pts xpts
2
Liverpool 82 59
3
Man City 57 63
4
Leicester 53 47
5
Chelsea 48 55
6
And I’m trying to add new columns that identify the team position by each column
I wanna get this:
JavaScript
1
6
1
teamId pts xpts №pts №xpts
2
Liverpool 82 59 1 2
3
Man City 57 63 2 1
4
Leicester 53 47 3 4
5
Chelsea 48 53 4 3
6
I tried to do something similar with the following code, but to no avail. The result is a list
JavaScript
1
2
1
df = [df.sort_values(by=i, ascending=False).assign(new_col=lambda x: range(1, len(df) + 1)) for i in df.columns]
2
Advertisement
Answer
Use DataFrame.rank
with DataFrame.add_prefix
and add new DataFrame to original DataFrame
by DataFrame.join
:
JavaScript
1
10
10
1
c = ['pts','xpts']
2
3
df = df.join(df[c].rank(method='dense', ascending=False).astype(int).add_prefix('N'))
4
print (df)
5
teamId pts xpts Npts Nxpts
6
0 Liverpool 82 59 1 2
7
1 Man City 57 63 2 1
8
2 Leicester 53 47 3 4
9
3 Chelsea 48 55 4 3
10
Another idea with for loop and f-string
s for new columns names:
JavaScript
1
11
11
1
c = ['pts','xpts']
2
3
for x in c:
4
df[f'N{x}'] = df[x].rank(method='dense', ascending=False).astype(int)
5
print (df)
6
teamId pts xpts Npts Nxpts
7
0 Liverpool 82 59 1 2
8
1 Man City 57 63 2 1
9
2 Leicester 53 47 3 4
10
3 Chelsea 48 55 4 3
11